diff --git a/owl-bot-staging/google-cloud-alloydb/v1/.coveragerc b/owl-bot-staging/google-cloud-alloydb/v1/.coveragerc new file mode 100644 index 000000000000..307a1b7e14a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/alloydb/__init__.py + google/cloud/alloydb/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-alloydb/v1/.flake8 b/owl-bot-staging/google-cloud-alloydb/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1/MANIFEST.in b/owl-bot-staging/google-cloud-alloydb/v1/MANIFEST.in new file mode 100644 index 000000000000..adf6f87e6e4d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/alloydb *.py +recursive-include google/cloud/alloydb_v1 *.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1/README.rst b/owl-bot-staging/google-cloud-alloydb/v1/README.rst new file mode 100644 index 000000000000..6a459d0a64f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Alloydb 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 Alloydb API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-alloydb/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/alloy_db_admin.rst b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/alloy_db_admin.rst new file mode 100644 index 000000000000..5ef26574dd58 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/alloy_db_admin.rst @@ -0,0 +1,10 @@ +AlloyDBAdmin +------------------------------ + +.. automodule:: google.cloud.alloydb_v1.services.alloy_db_admin + :members: + :inherited-members: + +.. automodule:: google.cloud.alloydb_v1.services.alloy_db_admin.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/services.rst b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/services.rst new file mode 100644 index 000000000000..f8842c56fe2f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Alloydb v1 API +======================================== +.. toctree:: + :maxdepth: 2 + + alloy_db_admin diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/types.rst b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/types.rst new file mode 100644 index 000000000000..8491d6038c4c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/alloydb_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Alloydb v1 API +===================================== + +.. automodule:: google.cloud.alloydb_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/conf.py b/owl-bot-staging/google-cloud-alloydb/v1/docs/conf.py new file mode 100644 index 000000000000..16113c8bdd60 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-alloydb 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-alloydb" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-alloydb-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-alloydb.tex", + u"google-cloud-alloydb 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-alloydb", + u"Google Cloud Alloydb 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-alloydb", + u"google-cloud-alloydb Documentation", + author, + "google-cloud-alloydb", + "GAPIC library for Google Cloud Alloydb API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1/docs/index.rst b/owl-bot-staging/google-cloud-alloydb/v1/docs/index.rst new file mode 100644 index 000000000000..66dec3cc1baa --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + alloydb_v1/services + alloydb_v1/types diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/__init__.py new file mode 100644 index 000000000000..aa9c5da03ac3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/__init__.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.alloydb_v1.services.alloy_db_admin.client import AlloyDBAdminClient +from google.cloud.alloydb_v1.services.alloy_db_admin.async_client import AlloyDBAdminAsyncClient + +from google.cloud.alloydb_v1.types.resources import AutomatedBackupPolicy +from google.cloud.alloydb_v1.types.resources import Backup +from google.cloud.alloydb_v1.types.resources import BackupSource +from google.cloud.alloydb_v1.types.resources import Cluster +from google.cloud.alloydb_v1.types.resources import ContinuousBackupConfig +from google.cloud.alloydb_v1.types.resources import ContinuousBackupInfo +from google.cloud.alloydb_v1.types.resources import ContinuousBackupSource +from google.cloud.alloydb_v1.types.resources import EncryptionConfig +from google.cloud.alloydb_v1.types.resources import EncryptionInfo +from google.cloud.alloydb_v1.types.resources import Instance +from google.cloud.alloydb_v1.types.resources import MigrationSource +from google.cloud.alloydb_v1.types.resources import SslConfig +from google.cloud.alloydb_v1.types.resources import SupportedDatabaseFlag +from google.cloud.alloydb_v1.types.resources import User +from google.cloud.alloydb_v1.types.resources import UserPassword +from google.cloud.alloydb_v1.types.resources import ClusterView +from google.cloud.alloydb_v1.types.resources import DatabaseVersion +from google.cloud.alloydb_v1.types.resources import InstanceView +from google.cloud.alloydb_v1.types.service import BatchCreateInstancesMetadata +from google.cloud.alloydb_v1.types.service import BatchCreateInstancesRequest +from google.cloud.alloydb_v1.types.service import BatchCreateInstancesResponse +from google.cloud.alloydb_v1.types.service import BatchCreateInstanceStatus +from google.cloud.alloydb_v1.types.service import CreateBackupRequest +from google.cloud.alloydb_v1.types.service import CreateClusterRequest +from google.cloud.alloydb_v1.types.service import CreateInstanceRequest +from google.cloud.alloydb_v1.types.service import CreateInstanceRequests +from google.cloud.alloydb_v1.types.service import CreateSecondaryClusterRequest +from google.cloud.alloydb_v1.types.service import CreateSecondaryInstanceRequest +from google.cloud.alloydb_v1.types.service import CreateUserRequest +from google.cloud.alloydb_v1.types.service import DeleteBackupRequest +from google.cloud.alloydb_v1.types.service import DeleteClusterRequest +from google.cloud.alloydb_v1.types.service import DeleteInstanceRequest +from google.cloud.alloydb_v1.types.service import DeleteUserRequest +from google.cloud.alloydb_v1.types.service import FailoverInstanceRequest +from google.cloud.alloydb_v1.types.service import GetBackupRequest +from google.cloud.alloydb_v1.types.service import GetClusterRequest +from google.cloud.alloydb_v1.types.service import GetInstanceRequest +from google.cloud.alloydb_v1.types.service import GetUserRequest +from google.cloud.alloydb_v1.types.service import InjectFaultRequest +from google.cloud.alloydb_v1.types.service import ListBackupsRequest +from google.cloud.alloydb_v1.types.service import ListBackupsResponse +from google.cloud.alloydb_v1.types.service import ListClustersRequest +from google.cloud.alloydb_v1.types.service import ListClustersResponse +from google.cloud.alloydb_v1.types.service import ListInstancesRequest +from google.cloud.alloydb_v1.types.service import ListInstancesResponse +from google.cloud.alloydb_v1.types.service import ListSupportedDatabaseFlagsRequest +from google.cloud.alloydb_v1.types.service import ListSupportedDatabaseFlagsResponse +from google.cloud.alloydb_v1.types.service import ListUsersRequest +from google.cloud.alloydb_v1.types.service import ListUsersResponse +from google.cloud.alloydb_v1.types.service import OperationMetadata +from google.cloud.alloydb_v1.types.service import PromoteClusterRequest +from google.cloud.alloydb_v1.types.service import RestartInstanceRequest +from google.cloud.alloydb_v1.types.service import RestoreClusterRequest +from google.cloud.alloydb_v1.types.service import UpdateBackupRequest +from google.cloud.alloydb_v1.types.service import UpdateClusterRequest +from google.cloud.alloydb_v1.types.service import UpdateInstanceRequest +from google.cloud.alloydb_v1.types.service import UpdateUserRequest + +__all__ = ('AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/py.typed b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/__init__.py new file mode 100644 index 000000000000..df46b6723fb9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/__init__.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.alloy_db_admin import AlloyDBAdminClient +from .services.alloy_db_admin import AlloyDBAdminAsyncClient + +from .types.resources import AutomatedBackupPolicy +from .types.resources import Backup +from .types.resources import BackupSource +from .types.resources import Cluster +from .types.resources import ContinuousBackupConfig +from .types.resources import ContinuousBackupInfo +from .types.resources import ContinuousBackupSource +from .types.resources import EncryptionConfig +from .types.resources import EncryptionInfo +from .types.resources import Instance +from .types.resources import MigrationSource +from .types.resources import SslConfig +from .types.resources import SupportedDatabaseFlag +from .types.resources import User +from .types.resources import UserPassword +from .types.resources import ClusterView +from .types.resources import DatabaseVersion +from .types.resources import InstanceView +from .types.service import BatchCreateInstancesMetadata +from .types.service import BatchCreateInstancesRequest +from .types.service import BatchCreateInstancesResponse +from .types.service import BatchCreateInstanceStatus +from .types.service import CreateBackupRequest +from .types.service import CreateClusterRequest +from .types.service import CreateInstanceRequest +from .types.service import CreateInstanceRequests +from .types.service import CreateSecondaryClusterRequest +from .types.service import CreateSecondaryInstanceRequest +from .types.service import CreateUserRequest +from .types.service import DeleteBackupRequest +from .types.service import DeleteClusterRequest +from .types.service import DeleteInstanceRequest +from .types.service import DeleteUserRequest +from .types.service import FailoverInstanceRequest +from .types.service import GetBackupRequest +from .types.service import GetClusterRequest +from .types.service import GetInstanceRequest +from .types.service import GetUserRequest +from .types.service import InjectFaultRequest +from .types.service import ListBackupsRequest +from .types.service import ListBackupsResponse +from .types.service import ListClustersRequest +from .types.service import ListClustersResponse +from .types.service import ListInstancesRequest +from .types.service import ListInstancesResponse +from .types.service import ListSupportedDatabaseFlagsRequest +from .types.service import ListSupportedDatabaseFlagsResponse +from .types.service import ListUsersRequest +from .types.service import ListUsersResponse +from .types.service import OperationMetadata +from .types.service import PromoteClusterRequest +from .types.service import RestartInstanceRequest +from .types.service import RestoreClusterRequest +from .types.service import UpdateBackupRequest +from .types.service import UpdateClusterRequest +from .types.service import UpdateInstanceRequest +from .types.service import UpdateUserRequest + +__all__ = ( + 'AlloyDBAdminAsyncClient', +'AlloyDBAdminClient', +'AutomatedBackupPolicy', +'Backup', +'BackupSource', +'BatchCreateInstanceStatus', +'BatchCreateInstancesMetadata', +'BatchCreateInstancesRequest', +'BatchCreateInstancesResponse', +'Cluster', +'ClusterView', +'ContinuousBackupConfig', +'ContinuousBackupInfo', +'ContinuousBackupSource', +'CreateBackupRequest', +'CreateClusterRequest', +'CreateInstanceRequest', +'CreateInstanceRequests', +'CreateSecondaryClusterRequest', +'CreateSecondaryInstanceRequest', +'CreateUserRequest', +'DatabaseVersion', +'DeleteBackupRequest', +'DeleteClusterRequest', +'DeleteInstanceRequest', +'DeleteUserRequest', +'EncryptionConfig', +'EncryptionInfo', +'FailoverInstanceRequest', +'GetBackupRequest', +'GetClusterRequest', +'GetInstanceRequest', +'GetUserRequest', +'InjectFaultRequest', +'Instance', +'InstanceView', +'ListBackupsRequest', +'ListBackupsResponse', +'ListClustersRequest', +'ListClustersResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListSupportedDatabaseFlagsRequest', +'ListSupportedDatabaseFlagsResponse', +'ListUsersRequest', +'ListUsersResponse', +'MigrationSource', +'OperationMetadata', +'PromoteClusterRequest', +'RestartInstanceRequest', +'RestoreClusterRequest', +'SslConfig', +'SupportedDatabaseFlag', +'UpdateBackupRequest', +'UpdateClusterRequest', +'UpdateInstanceRequest', +'UpdateUserRequest', +'User', +'UserPassword', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_metadata.json new file mode 100644 index 000000000000..d4cf589c05dd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_metadata.json @@ -0,0 +1,463 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.alloydb_v1", + "protoPackage": "google.cloud.alloydb.v1", + "schema": "1.0", + "services": { + "AlloyDBAdmin": { + "clients": { + "grpc": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlloyDBAdminAsyncClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "rest": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/py.typed b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/__init__.py new file mode 100644 index 000000000000..364ae3da06ba --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AlloyDBAdminClient +from .async_client import AlloyDBAdminAsyncClient + +__all__ = ( + 'AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py new file mode 100644 index 000000000000..6d0b0a8352f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py @@ -0,0 +1,4041 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.alloydb_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.alloydb_v1.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .client import AlloyDBAdminClient + + +class AlloyDBAdminAsyncClient: + """Service describing handlers for resources""" + + _client: AlloyDBAdminClient + + DEFAULT_ENDPOINT = AlloyDBAdminClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AlloyDBAdminClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(AlloyDBAdminClient.backup_path) + parse_backup_path = staticmethod(AlloyDBAdminClient.parse_backup_path) + cluster_path = staticmethod(AlloyDBAdminClient.cluster_path) + parse_cluster_path = staticmethod(AlloyDBAdminClient.parse_cluster_path) + crypto_key_version_path = staticmethod(AlloyDBAdminClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod(AlloyDBAdminClient.parse_crypto_key_version_path) + instance_path = staticmethod(AlloyDBAdminClient.instance_path) + parse_instance_path = staticmethod(AlloyDBAdminClient.parse_instance_path) + network_path = staticmethod(AlloyDBAdminClient.network_path) + parse_network_path = staticmethod(AlloyDBAdminClient.parse_network_path) + supported_database_flag_path = staticmethod(AlloyDBAdminClient.supported_database_flag_path) + parse_supported_database_flag_path = staticmethod(AlloyDBAdminClient.parse_supported_database_flag_path) + user_path = staticmethod(AlloyDBAdminClient.user_path) + parse_user_path = staticmethod(AlloyDBAdminClient.parse_user_path) + common_billing_account_path = staticmethod(AlloyDBAdminClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AlloyDBAdminClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AlloyDBAdminClient.common_folder_path) + parse_common_folder_path = staticmethod(AlloyDBAdminClient.parse_common_folder_path) + common_organization_path = staticmethod(AlloyDBAdminClient.common_organization_path) + parse_common_organization_path = staticmethod(AlloyDBAdminClient.parse_common_organization_path) + common_project_path = staticmethod(AlloyDBAdminClient.common_project_path) + parse_common_project_path = staticmethod(AlloyDBAdminClient.parse_common_project_path) + common_location_path = staticmethod(AlloyDBAdminClient.common_location_path) + parse_common_location_path = staticmethod(AlloyDBAdminClient.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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_info.__func__(AlloyDBAdminAsyncClient, 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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_file.__func__(AlloyDBAdminAsyncClient, 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 AlloyDBAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AlloyDBAdminClient).get_transport_class, type(AlloyDBAdminClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AlloyDBAdminTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, ~.AlloyDBAdminTransport]): 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 = AlloyDBAdminClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersAsyncPager: + r"""Lists Clusters 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 alloydb_v1 + + async def sample_list_clusters(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ListClustersRequest, dict]]): + The request object. Message for requesting list of + Clusters + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListClustersAsyncPager: + Message for response to listing + Clusters + 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 = service.ListClustersRequest(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_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_get_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GetClusterRequest, dict]]): + The request object. Message for getting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetClusterRequest(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_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1 + + async def sample_create_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.CreateClusterRequest, dict]]): + The request object. Message for creating a Cluster + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1.types.Cluster`): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_update_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.UpdateClusterRequest, dict]]): + The request object. Message for updating a Cluster + cluster (:class:`google.cloud.alloydb_v1.types.Cluster`): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 = service.UpdateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster, + 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(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_delete_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.DeleteClusterRequest, dict]]): + The request object. Message for deleting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 = service.DeleteClusterRequest(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_cluster, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_promote_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.PromoteClusterRequest, dict]]): + The request object. Message for promoting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.PromoteClusterRequest(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.promote_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, 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"""Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_restore_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.RestoreClusterRequest, dict]]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + request = service.RestoreClusterRequest(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.restore_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.CreateSecondaryClusterRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1.types.Cluster`): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateSecondaryClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_secondary_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesAsyncPager: + r"""Lists Instances 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 alloydb_v1 + + async def sample_list_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances + 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 = service.ListInstancesRequest(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_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_get_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GetInstanceRequest, dict]]): + The request object. Message for getting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetInstanceRequest(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_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1 + + async def sample_create_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.CreateInstanceRequest, dict]]): + The request object. Message for creating a Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1 + + async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.CreateSecondaryInstanceRequest, dict]]): + The request object. Message for creating a Secondary + Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateSecondaryInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_secondary_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, 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"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.BatchCreateInstancesRequest, dict]]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_instances, + 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_update_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.UpdateInstanceRequest, dict]]): + The request object. Message for updating a Instance + instance (:class:`google.cloud.alloydb_v1.types.Instance`): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 = service.UpdateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance, + 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(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_delete_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.DeleteInstanceRequest, dict]]): + The request object. Message for deleting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 = service.DeleteInstanceRequest(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_instance, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_failover_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.FailoverInstanceRequest, dict]]): + The request object. Message for triggering failover on an + Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.FailoverInstanceRequest(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.failover_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_inject_fault(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.InjectFaultRequest, dict]]): + The request object. Message for triggering fault + injection on an instance + fault_type (:class:`google.cloud.alloydb_v1.types.InjectFaultRequest.FaultType`): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 = service.InjectFaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_restart_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.RestartInstanceRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.RestartInstanceRequest(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.restart_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1 + + async def sample_list_backups(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1.types.ListBackupsRequest, dict]]): + The request object. Message for requesting list of + Backups + parent (:class:`str`): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListBackupsAsyncPager: + Message for response to listing + Backups + 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[service.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]] = (), + ) -> resources.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 alloydb_v1 + + async def sample_get_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1.types.GetBackupRequest, dict]]): + The request object. Message for getting a Backup + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1 + + async def sample_create_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1.types.CreateBackupRequest, dict]]): + The request object. Message for creating a Backup + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.alloydb_v1.types.Backup`): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. ID of the requesting + object. + + 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.alloydb_v1.types.Backup` Message + describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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=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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1 + + async def sample_update_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.UpdateBackupRequest, dict]]): + The request object. Message for updating a Backup + backup (:class:`google.cloud.alloydb_v1.types.Backup`): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1.types.Backup` Message + describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 = service.UpdateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_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(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1 + + async def sample_delete_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1.types.DeleteBackupRequest, dict]]): + The request object. Message for deleting a Backup + name (:class:`str`): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 = service.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=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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsAsyncPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1 + + async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsRequest, dict]]): + The request object. Message for listing the information + about the supported Database flags. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager: + Message for response to listing + SupportedDatabaseFlags. + 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 = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSupportedDatabaseFlagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersAsyncPager: + r"""Lists Users 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 alloydb_v1 + + async def sample_list_users(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ListUsersRequest, dict]]): + The request object. Message for requesting list of Users + parent (:class:`str`): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListUsersAsyncPager: + Message for response to listing Users + + 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 = service.ListUsersRequest(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_users, + 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.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_get_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GetUserRequest, dict]]): + The request object. Message for getting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetUserRequest(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_user, + 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_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_create_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.CreateUserRequest, dict]]): + The request object. Message for creating a User + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`google.cloud.alloydb_v1.types.User`): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 = service.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_update_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.UpdateUserRequest, dict]]): + The request object. Message for updating a User + user (:class:`google.cloud.alloydb_v1.types.User`): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 = service.UpdateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user, + 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(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_delete_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.DeleteUserRequest, dict]]): + The request object. Message for deleting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DeleteUserRequest(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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AlloyDBAdminAsyncClient": + 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__ = ( + "AlloyDBAdminAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/client.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/client.py new file mode 100644 index 000000000000..d1cab03775ed --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/client.py @@ -0,0 +1,4254 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.alloydb_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.alloydb_v1.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AlloyDBAdminGrpcTransport +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .transports.rest import AlloyDBAdminRestTransport + + +class AlloyDBAdminClientMeta(type): + """Metaclass for the AlloyDBAdmin 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[AlloyDBAdminTransport]] + _transport_registry["grpc"] = AlloyDBAdminGrpcTransport + _transport_registry["grpc_asyncio"] = AlloyDBAdminGrpcAsyncIOTransport + _transport_registry["rest"] = AlloyDBAdminRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AlloyDBAdminTransport]: + """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 AlloyDBAdminClient(metaclass=AlloyDBAdminClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "alloydb.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: + AlloyDBAdminClient: 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: + AlloyDBAdminClient: 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) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, 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.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str,str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_path(project: str,location: str,cluster: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?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 supported_database_flag_path(project: str,location: str,flag: str,) -> str: + """Returns a fully-qualified supported_database_flag string.""" + return "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + + @staticmethod + def parse_supported_database_flag_path(path: str) -> Dict[str,str]: + """Parses a supported_database_flag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/flags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(project: str,location: str,cluster: str,user: str,) -> str: + """Returns a fully-qualified user string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/users/(?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, AlloyDBAdminTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, AlloyDBAdminTransport]): 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, AlloyDBAdminTransport): + # transport is a AlloyDBAdminTransport 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_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersPager: + r"""Lists Clusters 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 alloydb_v1 + + def sample_list_clusters(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ListClustersRequest, dict]): + The request object. Message for requesting list of + Clusters + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListClustersPager: + Message for response to listing + Clusters + 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 service.ListClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListClustersRequest): + request = service.ListClustersRequest(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_clusters] + + # 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.ListClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_get_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetClusterRequest, dict]): + The request object. Message for getting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetClusterRequest): + request = service.GetClusterRequest(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_cluster] + + # Certain 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_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1 + + def sample_create_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.CreateClusterRequest, dict]): + The request object. Message for creating a Cluster + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateClusterRequest): + request = service.CreateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_update_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.UpdateClusterRequest, dict]): + The request object. Message for updating a Cluster + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 service.UpdateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateClusterRequest): + request = service.UpdateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_delete_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.DeleteClusterRequest, dict]): + The request object. Message for deleting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 service.DeleteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteClusterRequest): + request = service.DeleteClusterRequest(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_cluster] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_promote_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.PromoteClusterRequest, dict]): + The request object. Message for promoting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.PromoteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.PromoteClusterRequest): + request = service.PromoteClusterRequest(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.promote_cluster] + + # Certain 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, dict]] = 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 Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_restore_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.RestoreClusterRequest, dict]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.RestoreClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestoreClusterRequest): + request = service.RestoreClusterRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.CreateSecondaryClusterRequest, dict]): + The request object. + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateSecondaryClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryClusterRequest): + request = service.CreateSecondaryClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesPager: + r"""Lists Instances 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 alloydb_v1 + + def sample_list_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListInstancesPager: + Message for response to listing + Instances + 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 service.ListInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListInstancesRequest): + request = service.ListInstancesRequest(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_instances] + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_get_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetInstanceRequest, dict]): + The request object. Message for getting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetInstanceRequest): + request = service.GetInstanceRequest(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_instance] + + # Certain 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_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1 + + def sample_create_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.CreateInstanceRequest, dict]): + The request object. Message for creating a Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateInstanceRequest): + request = service.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1 + + def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.CreateSecondaryInstanceRequest, dict]): + The request object. Message for creating a Secondary + Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateSecondaryInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryInstanceRequest): + request = service.CreateSecondaryInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_batch_create_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.BatchCreateInstancesRequest, dict]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.BatchCreateInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.BatchCreateInstancesRequest): + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_instances] + + # 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_update_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.UpdateInstanceRequest, dict]): + The request object. Message for updating a Instance + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 service.UpdateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateInstanceRequest): + request = service.UpdateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_delete_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.DeleteInstanceRequest, dict]): + The request object. Message for deleting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 service.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteInstanceRequest): + request = service.DeleteInstanceRequest(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_instance] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_failover_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.FailoverInstanceRequest, dict]): + The request object. Message for triggering failover on an + Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.FailoverInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.FailoverInstanceRequest): + request = service.FailoverInstanceRequest(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.failover_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_inject_fault(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.InjectFaultRequest, dict]): + The request object. Message for triggering fault + injection on an instance + fault_type (google.cloud.alloydb_v1.types.InjectFaultRequest.FaultType): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 service.InjectFaultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.InjectFaultRequest): + request = service.InjectFaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_restart_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.RestartInstanceRequest, dict]): + The request object. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.RestartInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestartInstanceRequest): + request = service.RestartInstanceRequest(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.restart_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1 + + def sample_list_backups(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1.types.ListBackupsRequest, dict]): + The request object. Message for requesting list of + Backups + parent (str): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListBackupsPager: + Message for response to listing + Backups + 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 service.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListBackupsRequest): + request = service.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[service.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]] = (), + ) -> resources.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 alloydb_v1 + + def sample_get_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetBackupRequest, dict]): + The request object. Message for getting a Backup + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetBackupRequest): + request = service.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[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1 + + def sample_create_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1.types.CreateBackupRequest, dict]): + The request object. Message for creating a Backup + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.alloydb_v1.types.Backup): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. ID of the requesting + object. + + 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.alloydb_v1.types.Backup` Message + describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateBackupRequest): + request = service.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1 + + def sample_update_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.UpdateBackupRequest, dict]): + The request object. Message for updating a Backup + backup (google.cloud.alloydb_v1.types.Backup): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1.types.Backup` Message + describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 service.UpdateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateBackupRequest): + request = service.UpdateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1 + + def sample_delete_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1.types.DeleteBackupRequest, dict]): + The request object. Message for deleting a Backup + name (str): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 service.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteBackupRequest): + request = service.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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1 + + def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsRequest, dict]): + The request object. Message for listing the information + about the supported Database flags. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager: + Message for response to listing + SupportedDatabaseFlags. + 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 service.ListSupportedDatabaseFlagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSupportedDatabaseFlagsRequest): + request = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags] + + # 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.ListSupportedDatabaseFlagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersPager: + r"""Lists Users 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 alloydb_v1 + + def sample_list_users(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ListUsersRequest, dict]): + The request object. Message for requesting list of Users + parent (str): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1.services.alloy_db_admin.pagers.ListUsersPager: + Message for response to listing Users + + 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 service.ListUsersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListUsersRequest): + request = service.ListUsersRequest(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_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_get_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetUserRequest, dict]): + The request object. Message for getting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetUserRequest): + request = service.GetUserRequest(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_user] + + # Certain 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_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_create_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.CreateUserRequest, dict]): + The request object. Message for creating a User + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (google.cloud.alloydb_v1.types.User): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 service.CreateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateUserRequest): + request = service.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_update_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.UpdateUserRequest, dict]): + The request object. Message for updating a User + user (google.cloud.alloydb_v1.types.User): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 service.UpdateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateUserRequest): + request = service.UpdateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_delete_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.cloud.alloydb_v1.types.DeleteUserRequest, dict]): + The request object. Message for deleting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteUserRequest): + request = service.DeleteUserRequest(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_user] + + # Certain 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 __enter__(self) -> "AlloyDBAdminClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AlloyDBAdminClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py new file mode 100644 index 000000000000..a5da97abb13a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py @@ -0,0 +1,624 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service + + +class ListClustersPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListClustersResponse` + 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[..., service.ListClustersResponse], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListClustersResponse]: + 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[resources.Cluster]: + for page in self.pages: + yield from page.clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClustersAsyncPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListClustersResponse` + 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[service.ListClustersResponse]], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListClustersResponse]: + 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[resources.Cluster]: + async def async_generator(): + async for page in self.pages: + for response in page.clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListInstancesResponse` + 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[..., service.ListInstancesResponse], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListInstancesResponse]: + 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[resources.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListInstancesResponse` + 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[service.ListInstancesResponse]], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListInstancesResponse]: + 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[resources.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + 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.alloydb_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.alloydb_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[..., service.ListBackupsResponse], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.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[resources.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.alloydb_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.alloydb_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[service.ListBackupsResponse]], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.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[service.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[resources.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) + + +class ListSupportedDatabaseFlagsPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse` + 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[..., service.ListSupportedDatabaseFlagsResponse], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + for page in self.pages: + yield from page.supported_database_flags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSupportedDatabaseFlagsAsyncPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse` + 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[service.ListSupportedDatabaseFlagsResponse]], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + async def async_generator(): + async for page in self.pages: + for response in page.supported_database_flags: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListUsersResponse` + 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[..., service.ListUsersResponse], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListUsersResponse]: + 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[resources.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListUsersResponse` + 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[service.ListUsersResponse]], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListUsersResponse]: + 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[resources.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/__init__.py new file mode 100644 index 000000000000..9d544d8e4648 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AlloyDBAdminTransport +from .grpc import AlloyDBAdminGrpcTransport +from .grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .rest import AlloyDBAdminRestTransport +from .rest import AlloyDBAdminRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AlloyDBAdminTransport]] +_transport_registry['grpc'] = AlloyDBAdminGrpcTransport +_transport_registry['grpc_asyncio'] = AlloyDBAdminGrpcAsyncIOTransport +_transport_registry['rest'] = AlloyDBAdminRestTransport + +__all__ = ( + 'AlloyDBAdminTransport', + 'AlloyDBAdminGrpcTransport', + 'AlloyDBAdminGrpcAsyncIOTransport', + 'AlloyDBAdminRestTransport', + 'AlloyDBAdminRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py new file mode 100644 index 000000000000..ac12dc749d06 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py @@ -0,0 +1,646 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.alloydb_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.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AlloyDBAdminTransport(abc.ABC): + """Abstract transport class for AlloyDBAdmin.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'alloydb.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_clusters: gapic_v1.method.wrap_method( + self.list_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method.wrap_method( + self.get_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.promote_cluster: gapic_v1.method.wrap_method( + self.promote_cluster, + default_timeout=None, + client_info=client_info, + ), + self.restore_cluster: gapic_v1.method.wrap_method( + self.restore_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_cluster: gapic_v1.method.wrap_method( + self.create_secondary_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_instance: gapic_v1.method.wrap_method( + self.create_secondary_instance, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_instances: gapic_v1.method.wrap_method( + self.batch_create_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_instance: gapic_v1.method.wrap_method( + self.update_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.failover_instance: gapic_v1.method.wrap_method( + self.failover_instance, + default_timeout=None, + client_info=client_info, + ), + self.inject_fault: gapic_v1.method.wrap_method( + self.inject_fault, + default_timeout=None, + client_info=client_info, + ), + self.restart_instance: gapic_v1.method.wrap_method( + self.restart_instance, + default_timeout=None, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=None, + client_info=client_info, + ), + self.update_backup: gapic_v1.method.wrap_method( + self.update_backup, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.list_supported_database_flags: gapic_v1.method.wrap_method( + self.list_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + default_timeout=None, + client_info=client_info, + ), + self.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_timeout=None, + client_info=client_info, + ), + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + 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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Union[ + service.ListClustersResponse, + Awaitable[service.ListClustersResponse] + ]]: + raise NotImplementedError() + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Union[ + resources.Cluster, + Awaitable[resources.Cluster] + ]]: + raise NotImplementedError() + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Union[ + service.ListInstancesResponse, + Awaitable[service.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Union[ + resources.Instance, + Awaitable[resources.Instance] + ]]: + raise NotImplementedError() + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Union[ + service.ListBackupsResponse, + Awaitable[service.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Union[ + resources.Backup, + Awaitable[resources.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [service.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [service.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Union[ + service.ListSupportedDatabaseFlagsResponse, + Awaitable[service.ListSupportedDatabaseFlagsResponse] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Union[ + service.ListUsersResponse, + Awaitable[service.ListUsersResponse] + ]]: + raise NotImplementedError() + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AlloyDBAdminTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py new file mode 100644 index 000000000000..162ba253ba1c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py @@ -0,0 +1,1152 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import 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.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO + + +class AlloyDBAdminGrpcTransport(AlloyDBAdminTransport): + """gRPC backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + ~.ListClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + ~.Cluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + ~.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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + ~.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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + ~.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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + ~.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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + ~.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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + operations_pb2.Operation]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + ~.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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + ~.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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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.alloydb.v1.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + ~.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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + ~.ListSupportedDatabaseFlagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AlloyDBAdminGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8c7bcb0c4887 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py @@ -0,0 +1,1151 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.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.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .grpc import AlloyDBAdminGrpcTransport + + +class AlloyDBAdminGrpcAsyncIOTransport(AlloyDBAdminTransport): + """gRPC AsyncIO backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Awaitable[service.ListClustersResponse]]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + Awaitable[~.ListClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Awaitable[resources.Cluster]]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + Awaitable[~.Cluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + 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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + 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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Awaitable[service.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Awaitable[resources.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + 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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + 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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + 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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + 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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + 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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Awaitable[service.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Awaitable[resources.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.alloydb.v1.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + 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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Awaitable[service.ListSupportedDatabaseFlagsResponse]]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + Awaitable[~.ListSupportedDatabaseFlagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Awaitable[service.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'AlloyDBAdminGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py new file mode 100644 index 000000000000..9a3791238d6c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py @@ -0,0 +1,4094 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.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 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.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import AlloyDBAdminTransport, 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 AlloyDBAdminRestInterceptor: + """Interceptor for AlloyDBAdmin. + + 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 AlloyDBAdminRestTransport. + + .. code-block:: python + class MyCustomAlloyDBAdminInterceptor(AlloyDBAdminRestInterceptor): + def pre_batch_create_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_instances(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_failover_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_failover_instance(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_inject_fault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_inject_fault(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_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_supported_database_flags(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_supported_database_flags(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_promote_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_promote_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restart_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restart_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AlloyDBAdminRestTransport(interceptor=MyCustomAlloyDBAdminInterceptor()) + client = AlloyDBAdminClient(transport=transport) + + + """ + def pre_batch_create_instances(self, request: service.BatchCreateInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.BatchCreateInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_batch_create_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_backup(self, request: service.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_cluster(self, request: service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_instance(self, request: service.CreateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_cluster(self, request: service.CreateSecondaryClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_instance(self, request: service.CreateSecondaryInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_user(self, request: service.CreateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for create_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: service.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_cluster(self, request: service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_instance(self, request: service.DeleteInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_user(self, request: service.DeleteUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def pre_failover_instance(self, request: service.FailoverInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.FailoverInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for failover_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for failover_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: service.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_get_backup(self, response: resources.Backup) -> resources.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_cluster(self, request: service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: + """Post-rpc interceptor for get_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_instance(self, response: resources.Instance) -> resources.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_user(self, request: service.GetUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for get_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_inject_fault(self, request: service.InjectFaultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.InjectFaultRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for inject_fault + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_inject_fault(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for inject_fault + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: service.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_list_backups(self, response: service.ListBackupsResponse) -> service.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_clusters(self, request: service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_clusters(self, response: service.ListClustersResponse) -> service.ListClustersResponse: + """Post-rpc interceptor for list_clusters + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_instances(self, request: service.ListInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_instances(self, response: service.ListInstancesResponse) -> service.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_supported_database_flags(self, request: service.ListSupportedDatabaseFlagsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListSupportedDatabaseFlagsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_supported_database_flags(self, response: service.ListSupportedDatabaseFlagsResponse) -> service.ListSupportedDatabaseFlagsResponse: + """Post-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_users(self, request: service.ListUsersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListUsersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_users(self, response: service.ListUsersResponse) -> service.ListUsersResponse: + """Post-rpc interceptor for list_users + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_promote_cluster(self, request: service.PromoteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.PromoteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_promote_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restart_instance(self, request: service.RestartInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestartInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restart_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restart_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restart_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restore_cluster(self, request: service.RestoreClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestoreClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restore_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_backup(self, request: service.UpdateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_cluster(self, request: service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_instance(self, request: service.UpdateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_user(self, request: service.UpdateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for update_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AlloyDBAdminRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AlloyDBAdminRestInterceptor + + +class AlloyDBAdminRestTransport(AlloyDBAdminTransport): + """REST backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'alloydb.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[AlloyDBAdminRestInterceptor] = 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 AlloyDBAdminRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + '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 _BatchCreateInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("BatchCreateInstances") + + __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: service.BatchCreateInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch create instances method over HTTP. + + Args: + request (~.service.BatchCreateInstancesRequest): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:batchCreate', + 'body': 'requests', + }, + ] + request, metadata = self._interceptor.pre_batch_create_instances(request, metadata) + pb_request = service.BatchCreateInstancesRequest.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_batch_create_instances(resp) + return resp + + class _CreateBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.CreateBackupRequest): + The request object. Message for creating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = service.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 _CreateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create cluster method over HTTP. + + Args: + request (~.service.CreateClusterRequest): + The request object. Message for creating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_cluster(request, metadata) + pb_request = service.CreateClusterRequest.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_cluster(resp) + return resp + + class _CreateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.service.CreateInstanceRequest): + The request object. Message for creating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_instance(request, metadata) + pb_request = service.CreateInstanceRequest.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_instance(resp) + return resp + + class _CreateSecondaryCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary cluster method over HTTP. + + Args: + request (~.service.CreateSecondaryClusterRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/*}/clusters:createsecondary', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_cluster(request, metadata) + pb_request = service.CreateSecondaryClusterRequest.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_secondary_cluster(resp) + return resp + + class _CreateSecondaryInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary instance method over HTTP. + + Args: + request (~.service.CreateSecondaryInstanceRequest): + The request object. Message for creating a Secondary + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:createsecondary', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_instance(request, metadata) + pb_request = service.CreateSecondaryInstanceRequest.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_secondary_instance(resp) + return resp + + class _CreateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateUser") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the create user method over HTTP. + + Args: + request (~.service.CreateUserRequest): + The request object. Message for creating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/users', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_create_user(request, metadata) + pb_request = service.CreateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_user(resp) + return resp + + class _DeleteBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.DeleteBackupRequest): + The request object. Message for deleting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = service.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 _DeleteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteCluster") + + __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: service.DeleteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete cluster method over HTTP. + + Args: + request (~.service.DeleteClusterRequest): + The request object. Message for deleting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + pb_request = service.DeleteClusterRequest.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_cluster(resp) + return resp + + class _DeleteInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteInstance") + + __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: service.DeleteInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.service.DeleteInstanceRequest): + The request object. Message for deleting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + pb_request = service.DeleteInstanceRequest.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_instance(resp) + return resp + + class _DeleteUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteUser") + + __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: service.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.service.DeleteUserRequest): + The request object. Message for deleting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user(request, metadata) + pb_request = service.DeleteUserRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FailoverInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("FailoverInstance") + + __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: service.FailoverInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the failover instance method over HTTP. + + Args: + request (~.service.FailoverInstanceRequest): + The request object. Message for triggering failover on an + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:failover', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_failover_instance(request, metadata) + pb_request = service.FailoverInstanceRequest.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_failover_instance(resp) + return resp + + class _GetBackup(AlloyDBAdminRestStub): + 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: service.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.service.GetBackupRequest): + The request object. Message for getting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Backup: + Message describing Backup object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = service.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 = resources.Backup() + pb_resp = resources.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetCluster") + + __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: service.GetClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Cluster: + r"""Call the get cluster method over HTTP. + + Args: + request (~.service.GetClusterRequest): + The request object. Message for getting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_cluster(request, metadata) + pb_request = service.GetClusterRequest.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 = resources.Cluster() + pb_resp = resources.Cluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + return resp + + class _GetInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetInstance") + + __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: service.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.service.GetInstanceRequest): + The request object. Message for getting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = service.GetInstanceRequest.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 = resources.Instance() + pb_resp = resources.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetUser") + + __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: service.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the get user method over HTTP. + + Args: + request (~.service.GetUserRequest): + The request object. Message for getting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user(request, metadata) + pb_request = service.GetUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_user(resp) + return resp + + class _InjectFault(AlloyDBAdminRestStub): + def __hash__(self): + return hash("InjectFault") + + __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: service.InjectFaultRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the inject fault method over HTTP. + + Args: + request (~.service.InjectFaultRequest): + The request object. Message for triggering fault + injection on an instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_inject_fault(request, metadata) + pb_request = service.InjectFaultRequest.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_inject_fault(resp) + return resp + + class _ListBackups(AlloyDBAdminRestStub): + 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: service.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.service.ListBackupsRequest): + The request object. Message for requesting list of + Backups + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListBackupsResponse: + Message for response to listing + Backups + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = service.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 = service.ListBackupsResponse() + pb_resp = service.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListClusters(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListClusters") + + __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: service.ListClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListClustersResponse: + r"""Call the list clusters method over HTTP. + + Args: + request (~.service.ListClustersRequest): + The request object. Message for requesting list of + Clusters + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListClustersResponse: + Message for response to listing + Clusters + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/clusters', + }, + ] + request, metadata = self._interceptor.pre_list_clusters(request, metadata) + pb_request = service.ListClustersRequest.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 = service.ListClustersResponse() + pb_resp = service.ListClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + return resp + + class _ListInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListInstances") + + __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: service.ListInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.service.ListInstancesRequest): + The request object. Message for requesting list of + Instances + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListInstancesResponse: + Message for response to listing + Instances + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/instances', + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = service.ListInstancesRequest.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 = service.ListInstancesResponse() + pb_resp = service.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListSupportedDatabaseFlags(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListSupportedDatabaseFlags") + + __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: service.ListSupportedDatabaseFlagsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListSupportedDatabaseFlagsResponse: + r"""Call the list supported database + flags method over HTTP. + + Args: + request (~.service.ListSupportedDatabaseFlagsRequest): + The request object. Message for listing the information + about the supported Database flags. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListSupportedDatabaseFlagsResponse: + Message for response to listing + SupportedDatabaseFlags. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/supportedDatabaseFlags', + }, + ] + request, metadata = self._interceptor.pre_list_supported_database_flags(request, metadata) + pb_request = service.ListSupportedDatabaseFlagsRequest.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 = service.ListSupportedDatabaseFlagsResponse() + pb_resp = service.ListSupportedDatabaseFlagsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_supported_database_flags(resp) + return resp + + class _ListUsers(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListUsers") + + __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: service.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.service.ListUsersRequest): + The request object. Message for requesting list of Users + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListUsersResponse: + Message for response to listing Users + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/users', + }, + ] + request, metadata = self._interceptor.pre_list_users(request, metadata) + pb_request = service.ListUsersRequest.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 = service.ListUsersResponse() + pb_resp = service.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_users(resp) + return resp + + class _PromoteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("PromoteCluster") + + __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: service.PromoteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the promote cluster method over HTTP. + + Args: + request (~.service.PromoteClusterRequest): + The request object. Message for promoting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*}:promote', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_promote_cluster(request, metadata) + pb_request = service.PromoteClusterRequest.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_promote_cluster(resp) + return resp + + class _RestartInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestartInstance") + + __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: service.RestartInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restart instance method over HTTP. + + Args: + request (~.service.RestartInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/{name=projects/*/locations/*/clusters/*/instances/*}:restart', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restart_instance(request, metadata) + pb_request = service.RestartInstanceRequest.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_restart_instance(resp) + return resp + + class _RestoreCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestoreCluster") + + __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: service.RestoreClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore cluster method over HTTP. + + Args: + request (~.service.RestoreClusterRequest): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_cluster(request, metadata) + pb_request = service.RestoreClusterRequest.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_cluster(resp) + return resp + + class _UpdateBackup(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateBackup") + + __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: service.UpdateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update backup method over HTTP. + + Args: + request (~.service.UpdateBackupRequest): + The request object. Message for updating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{backup.name=projects/*/locations/*/backups/*}', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_update_backup(request, metadata) + pb_request = service.UpdateBackupRequest.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_backup(resp) + return resp + + class _UpdateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateCluster") + + __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: service.UpdateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.service.UpdateClusterRequest): + The request object. Message for updating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{cluster.name=projects/*/locations/*/clusters/*}', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + pb_request = service.UpdateClusterRequest.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_cluster(resp) + return resp + + class _UpdateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateInstance") + + __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: service.UpdateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. + + Args: + request (~.service.UpdateInstanceRequest): + The request object. Message for updating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_update_instance(request, metadata) + pb_request = service.UpdateInstanceRequest.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_instance(resp) + return resp + + class _UpdateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateUser") + + __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: service.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the update user method over HTTP. + + Args: + request (~.service.UpdateUserRequest): + The request object. Message for updating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{user.name=projects/*/locations/*/clusters/*/users/*}', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_update_user(request, metadata) + pb_request = service.UpdateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_user(resp) + return resp + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + 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._BatchCreateInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.CreateClusterRequest], + 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._CreateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + 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._CreateSecondaryCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + 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._CreateSecondaryInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + 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._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + 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._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + 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._InjectFault(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSupportedDatabaseFlags(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + 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._PromoteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + 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._RestartInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + 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._RestoreCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + 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._UpdateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + 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._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUser(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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(AlloyDBAdminRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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__=( + 'AlloyDBAdminRestTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/__init__.py new file mode 100644 index 000000000000..00fd477f6fed --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/__init__.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .resources import ( + AutomatedBackupPolicy, + Backup, + BackupSource, + Cluster, + ContinuousBackupConfig, + ContinuousBackupInfo, + ContinuousBackupSource, + EncryptionConfig, + EncryptionInfo, + Instance, + MigrationSource, + SslConfig, + SupportedDatabaseFlag, + User, + UserPassword, + ClusterView, + DatabaseVersion, + InstanceView, +) +from .service import ( + BatchCreateInstancesMetadata, + BatchCreateInstancesRequest, + BatchCreateInstancesResponse, + BatchCreateInstanceStatus, + CreateBackupRequest, + CreateClusterRequest, + CreateInstanceRequest, + CreateInstanceRequests, + CreateSecondaryClusterRequest, + CreateSecondaryInstanceRequest, + CreateUserRequest, + DeleteBackupRequest, + DeleteClusterRequest, + DeleteInstanceRequest, + DeleteUserRequest, + FailoverInstanceRequest, + GetBackupRequest, + GetClusterRequest, + GetInstanceRequest, + GetUserRequest, + InjectFaultRequest, + ListBackupsRequest, + ListBackupsResponse, + ListClustersRequest, + ListClustersResponse, + ListInstancesRequest, + ListInstancesResponse, + ListSupportedDatabaseFlagsRequest, + ListSupportedDatabaseFlagsResponse, + ListUsersRequest, + ListUsersResponse, + OperationMetadata, + PromoteClusterRequest, + RestartInstanceRequest, + RestoreClusterRequest, + UpdateBackupRequest, + UpdateClusterRequest, + UpdateInstanceRequest, + UpdateUserRequest, +) + +__all__ = ( + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/resources.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/resources.py new file mode 100644 index 000000000000..cca61318f69b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/resources.py @@ -0,0 +1,1925 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_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 +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1', + manifest={ + 'InstanceView', + 'ClusterView', + 'DatabaseVersion', + 'UserPassword', + 'MigrationSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'SslConfig', + 'AutomatedBackupPolicy', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'BackupSource', + 'ContinuousBackupSource', + 'Cluster', + 'Instance', + 'Backup', + 'SupportedDatabaseFlag', + 'User', + }, +) + + +class InstanceView(proto.Enum): + r"""View on Instance. Pass this enum to rpcs that returns an + Instance message to control which subsets of fields to get. + + Values: + INSTANCE_VIEW_UNSPECIFIED (0): + INSTANCE_VIEW_UNSPECIFIED Not specified, equivalent to + BASIC. + INSTANCE_VIEW_BASIC (1): + BASIC server responses for a primary or read + instance include all the relevant instance + details, excluding the details of each node in + the instance. The default value. + INSTANCE_VIEW_FULL (2): + FULL response is equivalent to BASIC for + primary instance (for now). For read pool + instance, this includes details of each node in + the pool. + """ + INSTANCE_VIEW_UNSPECIFIED = 0 + INSTANCE_VIEW_BASIC = 1 + INSTANCE_VIEW_FULL = 2 + + +class ClusterView(proto.Enum): + r"""View on Cluster. Pass this enum to rpcs that returns a + cluster message to control which subsets of fields to get. + + Values: + CLUSTER_VIEW_UNSPECIFIED (0): + CLUSTER_VIEW_UNSPECIFIED Not specified, equivalent to BASIC. + CLUSTER_VIEW_BASIC (1): + BASIC server responses include all the + relevant cluster details, excluding + Cluster.ContinuousBackupInfo.EarliestRestorableTime + and other view-specific fields. The default + value. + CLUSTER_VIEW_CONTINUOUS_BACKUP (2): + CONTINUOUS_BACKUP response returns all the fields from BASIC + plus the earliest restorable time if continuous backups are + enabled. May increase latency. + """ + CLUSTER_VIEW_UNSPECIFIED = 0 + CLUSTER_VIEW_BASIC = 1 + CLUSTER_VIEW_CONTINUOUS_BACKUP = 2 + + +class DatabaseVersion(proto.Enum): + r"""The supported database engine versions. + + Values: + DATABASE_VERSION_UNSPECIFIED (0): + This is an unknown database version. + POSTGRES_13 (1): + DEPRECATED - The database version is Postgres + 13. + POSTGRES_14 (2): + The database version is Postgres 14. + """ + DATABASE_VERSION_UNSPECIFIED = 0 + POSTGRES_13 = 1 + POSTGRES_14 = 2 + + +class UserPassword(proto.Message): + r"""The username/password for a database user. Used for + specifying initial users at cluster creation time. + + Attributes: + user (str): + The database username. + password (str): + The initial password for the user. + """ + + user: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MigrationSource(proto.Message): + r"""Subset of the source instance configuration that is available + when reading the cluster resource. + + Attributes: + host_port (str): + Output only. The host and port of the + on-premises instance in host:port format + reference_id (str): + Output only. Place holder for the external + source identifier(e.g DMS job name) that created + the cluster. + source_type (google.cloud.alloydb_v1.types.MigrationSource.MigrationSourceType): + Output only. Type of migration source. + """ + class MigrationSourceType(proto.Enum): + r"""Denote the type of migration source that created this + cluster. + + Values: + MIGRATION_SOURCE_TYPE_UNSPECIFIED (0): + Migration source is unknown. + DMS (1): + DMS source means the cluster was created via + DMS migration job. + """ + MIGRATION_SOURCE_TYPE_UNSPECIFIED = 0 + DMS = 1 + + host_port: str = proto.Field( + proto.STRING, + number=1, + ) + reference_id: str = proto.Field( + proto.STRING, + number=2, + ) + source_type: MigrationSourceType = proto.Field( + proto.ENUM, + number=3, + enum=MigrationSourceType, + ) + + +class EncryptionConfig(proto.Message): + r"""EncryptionConfig describes the encryption config of a cluster + or a backup that is encrypted with a CMEK (customer-managed + encryption key). + + Attributes: + kms_key_name (str): + The fully-qualified resource name of the KMS key. Each Cloud + KMS key is regionalized and has the following format: + projects/[PROJECT]/locations/[REGION]/keyRings/[RING]/cryptoKeys/[KEY_NAME] + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptionInfo(proto.Message): + r"""EncryptionInfo describes the encryption information of a + cluster or a backup. + + Attributes: + encryption_type (google.cloud.alloydb_v1.types.EncryptionInfo.Type): + Output only. Type of encryption. + kms_key_versions (MutableSequence[str]): + Output only. Cloud KMS key versions that are + being used to protect the database or the + backup. + """ + class Type(proto.Enum): + r"""Possible encryption types. + + Values: + TYPE_UNSPECIFIED (0): + Encryption type not specified. Defaults to + GOOGLE_DEFAULT_ENCRYPTION. + GOOGLE_DEFAULT_ENCRYPTION (1): + The data is encrypted at rest with a key that + is fully managed by Google. No key version will + be populated. This is the default state. + CUSTOMER_MANAGED_ENCRYPTION (2): + The data is encrypted at rest with a key that + is managed by the customer. KMS key versions + will be populated. + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DEFAULT_ENCRYPTION = 1 + CUSTOMER_MANAGED_ENCRYPTION = 2 + + encryption_type: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class SslConfig(proto.Message): + r"""SSL configuration. + + Attributes: + ssl_mode (google.cloud.alloydb_v1.types.SslConfig.SslMode): + Optional. SSL mode. Specifies client-server + SSL/TLS connection behavior. + ca_source (google.cloud.alloydb_v1.types.SslConfig.CaSource): + Optional. Certificate Authority (CA) source. Only + CA_SOURCE_MANAGED is supported currently, and is the default + value. + """ + class SslMode(proto.Enum): + r"""SSL mode options. + + Values: + SSL_MODE_UNSPECIFIED (0): + SSL mode not specified. Defaults to ENCRYPTED_ONLY. + SSL_MODE_ALLOW (1): + SSL connections are optional. CA verification + not enforced. + SSL_MODE_REQUIRE (2): + SSL connections are required. CA verification + not enforced. Clients may use locally + self-signed certificates (default psql client + behavior). + SSL_MODE_VERIFY_CA (3): + SSL connections are required. CA verification + enforced. Clients must have certificates signed + by a Cluster CA, e.g. via + GenerateClientCertificate. + ALLOW_UNENCRYPTED_AND_ENCRYPTED (4): + SSL connections are optional. CA verification + not enforced. + ENCRYPTED_ONLY (5): + SSL connections are required. CA verification + not enforced. + """ + SSL_MODE_UNSPECIFIED = 0 + SSL_MODE_ALLOW = 1 + SSL_MODE_REQUIRE = 2 + SSL_MODE_VERIFY_CA = 3 + ALLOW_UNENCRYPTED_AND_ENCRYPTED = 4 + ENCRYPTED_ONLY = 5 + + class CaSource(proto.Enum): + r"""Certificate Authority (CA) source for SSL/TLS certificates. + + Values: + CA_SOURCE_UNSPECIFIED (0): + Certificate Authority (CA) source not specified. Defaults to + CA_SOURCE_MANAGED. + CA_SOURCE_MANAGED (1): + Certificate Authority (CA) managed by the + AlloyDB Cluster. + """ + CA_SOURCE_UNSPECIFIED = 0 + CA_SOURCE_MANAGED = 1 + + ssl_mode: SslMode = proto.Field( + proto.ENUM, + number=1, + enum=SslMode, + ) + ca_source: CaSource = proto.Field( + proto.ENUM, + number=2, + enum=CaSource, + ) + + +class AutomatedBackupPolicy(proto.Message): + r"""Message describing the user-specified automated backup + policy. + All fields in the automated backup policy are optional. Defaults + for each field are provided if they are not set. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + weekly_schedule (google.cloud.alloydb_v1.types.AutomatedBackupPolicy.WeeklySchedule): + Weekly schedule for the Backup. + + This field is a member of `oneof`_ ``schedule``. + time_based_retention (google.cloud.alloydb_v1.types.AutomatedBackupPolicy.TimeBasedRetention): + Time-based Backup retention policy. + + This field is a member of `oneof`_ ``retention``. + quantity_based_retention (google.cloud.alloydb_v1.types.AutomatedBackupPolicy.QuantityBasedRetention): + Quantity-based Backup retention policy to + retain recent backups. + + This field is a member of `oneof`_ ``retention``. + enabled (bool): + Whether automated automated backups are + enabled. If not set, defaults to true. + + This field is a member of `oneof`_ ``_enabled``. + backup_window (google.protobuf.duration_pb2.Duration): + The length of the time window during which a + backup can be taken. If a backup does not + succeed within this time window, it will be + canceled and considered failed. + + The backup window must be at least 5 minutes + long. There is no upper bound on the window. If + not set, it defaults to 1 hour. + encryption_config (google.cloud.alloydb_v1.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backups with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + location (str): + The location where the backup will be stored. + Currently, the only supported option is to store + the backup in the same region as the cluster. + + If empty, defaults to the region of the cluster. + labels (MutableMapping[str, str]): + Labels to apply to backups created using this + configuration. + """ + + class WeeklySchedule(proto.Message): + r"""A weekly schedule starts a backup at prescribed start times within a + day, for the specified days of the week. + + The weekly schedule message is flexible and can be used to create + many types of schedules. For example, to have a daily backup that + starts at 22:00, configure the ``start_times`` field to have one + element "22:00" and the ``days_of_week`` field to have all seven + days of the week. + + Attributes: + start_times (MutableSequence[google.type.timeofday_pb2.TimeOfDay]): + The times during the day to start a backup. + The start times are assumed to be in UTC and to + be an exact hour (e.g., 04:00:00). + + If no start times are provided, a single fixed + start time is chosen arbitrarily. + days_of_week (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + The days of the week to perform a backup. + + If this field is left empty, the default of + every day of the week is used. + """ + + start_times: MutableSequence[timeofday_pb2.TimeOfDay] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=timeofday_pb2.TimeOfDay, + ) + days_of_week: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + class TimeBasedRetention(proto.Message): + r"""A time based retention policy specifies that all backups + within a certain time period should be retained. + + Attributes: + retention_period (google.protobuf.duration_pb2.Duration): + The retention period. + """ + + retention_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class QuantityBasedRetention(proto.Message): + r"""A quantity based policy specifies that a certain number of + the most recent successful backups should be retained. + + Attributes: + count (int): + The number of backups to retain. + """ + + count: int = proto.Field( + proto.INT32, + number=1, + ) + + weekly_schedule: WeeklySchedule = proto.Field( + proto.MESSAGE, + number=2, + oneof='schedule', + message=WeeklySchedule, + ) + time_based_retention: TimeBasedRetention = proto.Field( + proto.MESSAGE, + number=4, + oneof='retention', + message=TimeBasedRetention, + ) + quantity_based_retention: QuantityBasedRetention = proto.Field( + proto.MESSAGE, + number=5, + oneof='retention', + message=QuantityBasedRetention, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + backup_window: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='EncryptionConfig', + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class ContinuousBackupConfig(proto.Message): + r"""ContinuousBackupConfig describes the continuous backups + recovery configurations of a cluster. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Whether ContinuousBackup is enabled. + + This field is a member of `oneof`_ ``_enabled``. + recovery_window_days (int): + The number of days that are eligible to + restore from using PITR. To support the entire + recovery window, backups and logs are retained + for one day more than the recovery window. If + not set, defaults to 14 days. + encryption_config (google.cloud.alloydb_v1.types.EncryptionConfig): + The encryption config can be specified to + encrypt the backups with a customer-managed + encryption key (CMEK). When this field is not + specified, the backup will then use default + encryption scheme to protect the user data. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + recovery_window_days: int = proto.Field( + proto.INT32, + number=4, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='EncryptionConfig', + ) + + +class ContinuousBackupInfo(proto.Message): + r"""ContinuousBackupInfo describes the continuous backup + properties of a cluster. + + Attributes: + encryption_info (google.cloud.alloydb_v1.types.EncryptionInfo): + Output only. The encryption information for + the WALs and backups required for + ContinuousBackup. + enabled_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When ContinuousBackup was most + recently enabled. Set to null if + ContinuousBackup is not enabled. + schedule (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + Output only. Days of the week on which a + continuous backup is taken. Output only field. + Ignored if passed into the request. + earliest_restorable_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The earliest restorable time + that can be restored to. Output only field. + """ + + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='EncryptionInfo', + ) + enabled_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + schedule: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=dayofweek_pb2.DayOfWeek, + ) + earliest_restorable_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class BackupSource(proto.Message): + r"""Message describing a BackupSource. + + Attributes: + backup_uid (str): + Output only. The system-generated UID of the + backup which was used to create this resource. + The UID is generated when the backup is created, + and it is retained until the backup is deleted. + backup_name (str): + Required. The name of the backup resource with the format: + + - projects/{project}/locations/{region}/backups/{backup_id} + """ + + backup_uid: str = proto.Field( + proto.STRING, + number=2, + ) + backup_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ContinuousBackupSource(proto.Message): + r"""Message describing a ContinuousBackupSource. + + Attributes: + cluster (str): + Required. The source cluster from which to + restore. This cluster must have continuous + backup enabled for this operation to succeed. + For the required format, see the comment on the + Cluster.name field. + point_in_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The point in time to restore to. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + point_in_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Cluster(proto.Message): + r"""A cluster is a collection of regional AlloyDB resources. It + can include a primary instance and one or more read pool + instances. All cluster resources share a storage layer, which + scales as needed. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1.types.BackupSource): + Output only. Cluster created from backup. + + This field is a member of `oneof`_ ``source``. + migration_source (google.cloud.alloydb_v1.types.MigrationSource): + Output only. Cluster created via DMS + migration. + + This field is a member of `oneof`_ ``source``. + name (str): + Output only. The name of the cluster resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + where the cluster ID segment should satisfy the regex + expression ``[a-z0-9-]+``. For more details see + https://google.aip.dev/122. The prefix of the cluster + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Cluster. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1.types.Cluster.State): + Output only. The current serving state of the + cluster. + cluster_type (google.cloud.alloydb_v1.types.Cluster.ClusterType): + Output only. The type of the cluster. This is an output-only + field and it's populated at the Cluster creation time or the + Cluster promotion time. The cluster type is determined by + which RPC was used to create the cluster (i.e. + ``CreateCluster`` vs. ``CreateSecondaryCluster`` + database_version (google.cloud.alloydb_v1.types.DatabaseVersion): + Optional. The database engine major version. + This is an optional field and it is populated at + the Cluster creation time. If a database version + is not supplied at cluster creation time, then a + default database version will be used. + network_config (google.cloud.alloydb_v1.types.Cluster.NetworkConfig): + + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project}/global/networks/{network_id}". This is + required to create a cluster. Deprecated, use + network_config.network instead. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Cluster does not + match the user's intended state, and the service + is actively updating the resource to reconcile + them. This can happen due to user-triggered + updates or system actions like failover or + maintenance. + initial_user (google.cloud.alloydb_v1.types.UserPassword): + Input only. Initial user to setup during cluster creation. + Required. If used in ``RestoreCluster`` this is ignored. + automated_backup_policy (google.cloud.alloydb_v1.types.AutomatedBackupPolicy): + The automated backup policy for this cluster. + + If no policy is provided then the default policy + will be used. If backups are supported for the + cluster, the default policy takes one backup a + day, has a backup window of 1 hour, and retains + backups for 14 days. For more information on the + defaults, consult the documentation for the + message type. + ssl_config (google.cloud.alloydb_v1.types.SslConfig): + SSL configuration for this AlloyDB cluster. + encryption_config (google.cloud.alloydb_v1.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the data disks and other + persistent data resources of a cluster with a + customer-managed encryption key (CMEK). When + this field is not specified, the cluster will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1.types.EncryptionInfo): + Output only. The encryption information for + the cluster. + continuous_backup_config (google.cloud.alloydb_v1.types.ContinuousBackupConfig): + Optional. Continuous backup configuration for + this cluster. + continuous_backup_info (google.cloud.alloydb_v1.types.ContinuousBackupInfo): + Output only. Continuous backup properties for + this cluster. + secondary_config (google.cloud.alloydb_v1.types.Cluster.SecondaryConfig): + Cross Region replication config specific to + SECONDARY cluster. + primary_config (google.cloud.alloydb_v1.types.Cluster.PrimaryConfig): + Output only. Cross Region replication config + specific to PRIMARY cluster. + """ + class State(proto.Enum): + r"""Cluster State + + Values: + STATE_UNSPECIFIED (0): + The state of the cluster is unknown. + READY (1): + The cluster is active and running. + STOPPED (2): + The cluster is stopped. All instances in the + cluster are stopped. Customers can start a + stopped cluster at any point and all their + instances will come back to life with same names + and IP resources. In this state, customer pays + for storage. + Associated backups could also be present in a + stopped cluster. + EMPTY (3): + The cluster is empty and has no associated + resources. All instances, associated storage and + backups have been deleted. + CREATING (4): + The cluster is being created. + DELETING (5): + The cluster is being deleted. + FAILED (6): + The creation of the cluster failed. + BOOTSTRAPPING (7): + The cluster is bootstrapping with data from + some other source. Direct mutations to the + cluster (e.g. adding read pool) are not allowed. + MAINTENANCE (8): + The cluster is under maintenance. AlloyDB + regularly performs maintenance and upgrades on + customer clusters. Updates on the cluster are + not allowed while the cluster is in this state. + PROMOTING (9): + The cluster is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + EMPTY = 3 + CREATING = 4 + DELETING = 5 + FAILED = 6 + BOOTSTRAPPING = 7 + MAINTENANCE = 8 + PROMOTING = 9 + + class ClusterType(proto.Enum): + r"""Type of Cluster + + Values: + CLUSTER_TYPE_UNSPECIFIED (0): + The type of the cluster is unknown. + PRIMARY (1): + Primary cluster that support read and write + operations. + SECONDARY (2): + Secondary cluster that is replicating from + another region. This only supports read. + """ + CLUSTER_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + SECONDARY = 2 + + class NetworkConfig(proto.Message): + r"""Metadata related to network configuration. + + Attributes: + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project_number}/global/networks/{network_id}". + This is required to create a cluster. + allocated_ip_range (str): + Optional. Name of the allocated IP range for the private IP + AlloyDB cluster, for example: + "google-managed-services-default". If set, the instance IPs + for this cluster will be created in the allocated range. The + range name must comply with RFC 1035. Specifically, the name + must be 1-63 characters long and match the regular + expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. Field name is + intended to be consistent with CloudSQL. + """ + + network: str = proto.Field( + proto.STRING, + number=1, + ) + allocated_ip_range: str = proto.Field( + proto.STRING, + number=2, + ) + + class SecondaryConfig(proto.Message): + r"""Configuration information for the secondary cluster. This + should be set if and only if the cluster is of type SECONDARY. + + Attributes: + primary_cluster_name (str): + The name of the primary cluster name with the format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + """ + + primary_cluster_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class PrimaryConfig(proto.Message): + r"""Configuration for the primary cluster. It has the list of + clusters that are replicating from this cluster. This should be + set if and only if the cluster is of type PRIMARY. + + Attributes: + secondary_cluster_names (MutableSequence[str]): + Output only. Names of the clusters that are + replicating from this cluster. + """ + + secondary_cluster_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + backup_source: 'BackupSource' = proto.Field( + proto.MESSAGE, + number=15, + oneof='source', + message='BackupSource', + ) + migration_source: 'MigrationSource' = proto.Field( + proto.MESSAGE, + number=16, + oneof='source', + message='MigrationSource', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + cluster_type: ClusterType = proto.Field( + proto.ENUM, + number=24, + enum=ClusterType, + ) + database_version: 'DatabaseVersion' = proto.Field( + proto.ENUM, + number=9, + enum='DatabaseVersion', + ) + network_config: NetworkConfig = proto.Field( + proto.MESSAGE, + number=29, + message=NetworkConfig, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=13, + ) + initial_user: 'UserPassword' = proto.Field( + proto.MESSAGE, + number=14, + message='UserPassword', + ) + automated_backup_policy: 'AutomatedBackupPolicy' = proto.Field( + proto.MESSAGE, + number=17, + message='AutomatedBackupPolicy', + ) + ssl_config: 'SslConfig' = proto.Field( + proto.MESSAGE, + number=18, + message='SslConfig', + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=19, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionInfo', + ) + continuous_backup_config: 'ContinuousBackupConfig' = proto.Field( + proto.MESSAGE, + number=27, + message='ContinuousBackupConfig', + ) + continuous_backup_info: 'ContinuousBackupInfo' = proto.Field( + proto.MESSAGE, + number=28, + message='ContinuousBackupInfo', + ) + secondary_config: SecondaryConfig = proto.Field( + proto.MESSAGE, + number=22, + message=SecondaryConfig, + ) + primary_config: PrimaryConfig = proto.Field( + proto.MESSAGE, + number=23, + message=PrimaryConfig, + ) + + +class Instance(proto.Message): + r"""An Instance is a computing unit that an end customer can + connect to. It's the main unit of computing resources in + AlloyDB. + + Attributes: + name (str): + Output only. The name of the instance resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id}/instances/{instance_id} + where the cluster and instance ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the instance + resource name is the name of the parent resource: + - projects/{project}/locations/{region}/clusters/{cluster_id} + display_name (str): + User-settable and human-readable display name + for the Instance. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1.types.Instance.State): + Output only. The current serving state of the + instance. + instance_type (google.cloud.alloydb_v1.types.Instance.InstanceType): + Required. The type of the instance. Specified + at creation time. + machine_config (google.cloud.alloydb_v1.types.Instance.MachineConfig): + Configurations for the machines that host the + underlying database engine. + availability_type (google.cloud.alloydb_v1.types.Instance.AvailabilityType): + Availability type of an Instance. If empty, defaults to + REGIONAL for primary instances. For read pools, + availability_type is always UNSPECIFIED. Instances in the + read pools are evenly distributed across available zones + within the region (i.e. read pools with more than one node + will have a node in at least two zones). + gce_zone (str): + The Compute Engine zone that the instance + should serve from, per + https://cloud.google.com/compute/docs/regions-zones + This can ONLY be specified for ZONAL instances. + If present for a REGIONAL instance, an error + will be thrown. If this is absent for a ZONAL + instance, instance is created in a random zone + with available capacity. + database_flags (MutableMapping[str, str]): + Database flags. Set at instance level. + + - They are copied from primary instance on read instance + creation. + - Read instances can set new or override existing flags + that are relevant for reads, e.g. for enabling columnar + cache on a read instance. Flags set on read instance may + or may not be present on primary. + + This is a list of "key": "value" pairs. "key": The name of + the flag. These flags are passed at instance setup time, so + include both server options and system variables for + Postgres. Flags are specified with underscores, not hyphens. + "value": The value of the flag. Booleans are set to **on** + for true and **off** for false. This field must be omitted + if the flag doesn't take a value. + writable_node (google.cloud.alloydb_v1.types.Instance.Node): + Output only. This is set for the read-write + VM of the PRIMARY instance only. + nodes (MutableSequence[google.cloud.alloydb_v1.types.Instance.Node]): + Output only. List of available read-only VMs + in this instance, including the standby for a + PRIMARY instance. + query_insights_config (google.cloud.alloydb_v1.types.Instance.QueryInsightsInstanceConfig): + Configuration for query insights. + read_pool_config (google.cloud.alloydb_v1.types.Instance.ReadPoolConfig): + Read pool specific config. + ip_address (str): + Output only. The IP address for the Instance. + This is the connection endpoint for an end-user + application. + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Instance does + not match the user's intended state, and the + service is actively updating the resource to + reconcile them. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + client_connection_config (google.cloud.alloydb_v1.types.Instance.ClientConnectionConfig): + Optional. Client connection specific + configurations + """ + class State(proto.Enum): + r"""Instance State + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + READY (1): + The instance is active and running. + STOPPED (2): + The instance is stopped. Instance name and IP + resources are preserved. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + MAINTENANCE (5): + The instance is down for maintenance. + FAILED (6): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance. Note: Instances in this state would + tried to be auto-repaired. And Customers should + be able to restart, update or delete these + instances. + BOOTSTRAPPING (8): + Index 7 is used in the producer apis for ROLLED_BACK state. + Keeping that index unused in case that state also needs to + exposed via consumer apis in future. The instance has been + configured to sync data from some other source. + PROMOTING (9): + The instance is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + CREATING = 3 + DELETING = 4 + MAINTENANCE = 5 + FAILED = 6 + BOOTSTRAPPING = 8 + PROMOTING = 9 + + class InstanceType(proto.Enum): + r"""Type of an Instance + + Values: + INSTANCE_TYPE_UNSPECIFIED (0): + The type of the instance is unknown. + PRIMARY (1): + PRIMARY instances support read and write + operations. + READ_POOL (2): + READ POOL instances support read operations only. Each read + pool instance consists of one or more homogeneous nodes. + + - Read pool of size 1 can only have zonal availability. + - Read pools with node count of 2 or more can have regional + availability (nodes are present in 2 or more zones in a + region). + SECONDARY (3): + SECONDARY instances support read operations + only. SECONDARY instance is a cross-region read + replica + """ + INSTANCE_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + READ_POOL = 2 + SECONDARY = 3 + + class AvailabilityType(proto.Enum): + r"""The Availability type of an instance. Potential values: + + - ZONAL: The instance serves data from only one zone. Outages in + that zone affect instance availability. + - REGIONAL: The instance can serve data from more than one zone + in a region (it is highly available). + + Values: + AVAILABILITY_TYPE_UNSPECIFIED (0): + This is an unknown Availability type. + ZONAL (1): + Zonal available instance. + REGIONAL (2): + Regional (or Highly) available instance. + """ + AVAILABILITY_TYPE_UNSPECIFIED = 0 + ZONAL = 1 + REGIONAL = 2 + + class MachineConfig(proto.Message): + r"""MachineConfig describes the configuration of a machine. + + Attributes: + cpu_count (int): + The number of CPU's in the VM instance. + """ + + cpu_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class Node(proto.Message): + r"""Details of a single node in the instance. + Nodes in an AlloyDB instance are ephemereal, they can change + during update, failover, autohealing and resize operations. + + Attributes: + zone_id (str): + The Compute Engine zone of the VM e.g. + "us-central1-b". + id (str): + The identifier of the VM e.g. + "test-read-0601-407e52be-ms3l". + ip (str): + The private IP address of the VM e.g. + "10.57.0.34". + state (str): + Determined by state of the compute VM and + postgres-service health. Compute VM state can + have values listed in + https://cloud.google.com/compute/docs/instances/instance-life-cycle + and postgres-service health can have values: + HEALTHY and UNHEALTHY. + """ + + zone_id: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + ip: str = proto.Field( + proto.STRING, + number=3, + ) + state: str = proto.Field( + proto.STRING, + number=4, + ) + + class QueryInsightsInstanceConfig(proto.Message): + r"""QueryInsights Instance specific configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + record_application_tags (bool): + Record application tags for an instance. + This flag is turned "on" by default. + + This field is a member of `oneof`_ ``_record_application_tags``. + record_client_address (bool): + Record client address for an instance. Client + address is PII information. This flag is turned + "on" by default. + + This field is a member of `oneof`_ ``_record_client_address``. + query_string_length (int): + Query string length. The default value is + 1024. Any integer between 256 and 4500 is + considered valid. + query_plans_per_minute (int): + Number of query execution plans captured by + Insights per minute for all queries combined. + The default value is 5. Any integer between 0 + and 20 is considered valid. + + This field is a member of `oneof`_ ``_query_plans_per_minute``. + """ + + record_application_tags: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + record_client_address: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + query_string_length: int = proto.Field( + proto.UINT32, + number=4, + ) + query_plans_per_minute: int = proto.Field( + proto.UINT32, + number=5, + optional=True, + ) + + class ReadPoolConfig(proto.Message): + r"""Configuration for a read pool instance. + + Attributes: + node_count (int): + Read capacity, i.e. number of nodes in a read + pool instance. + """ + + node_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class ClientConnectionConfig(proto.Message): + r"""Client connection configuration + + Attributes: + require_connectors (bool): + Optional. Configuration to enforce connectors + only (ex: AuthProxy) connections to the + database. + ssl_config (google.cloud.alloydb_v1.types.SslConfig): + Optional. SSL config option for this + instance. + """ + + require_connectors: bool = proto.Field( + proto.BOOL, + number=1, + ) + ssl_config: 'SslConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='SslConfig', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + instance_type: InstanceType = proto.Field( + proto.ENUM, + number=9, + enum=InstanceType, + ) + machine_config: MachineConfig = proto.Field( + proto.MESSAGE, + number=10, + message=MachineConfig, + ) + availability_type: AvailabilityType = proto.Field( + proto.ENUM, + number=11, + enum=AvailabilityType, + ) + gce_zone: str = proto.Field( + proto.STRING, + number=12, + ) + database_flags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + writable_node: Node = proto.Field( + proto.MESSAGE, + number=19, + message=Node, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=Node, + ) + query_insights_config: QueryInsightsInstanceConfig = proto.Field( + proto.MESSAGE, + number=21, + message=QueryInsightsInstanceConfig, + ) + read_pool_config: ReadPoolConfig = proto.Field( + proto.MESSAGE, + number=14, + message=ReadPoolConfig, + ) + ip_address: str = proto.Field( + proto.STRING, + number=15, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=16, + ) + etag: str = proto.Field( + proto.STRING, + number=17, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + client_connection_config: ClientConnectionConfig = proto.Field( + proto.MESSAGE, + number=23, + message=ClientConnectionConfig, + ) + + +class Backup(proto.Message): + r"""Message describing Backup object + + Attributes: + name (str): + Output only. The name of the backup resource with the + format: + + - projects/{project}/locations/{region}/backups/{backup_id} + where the cluster and backup ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the backup + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Backup. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1.types.Backup.State): + Output only. The current state of the backup. + type_ (google.cloud.alloydb_v1.types.Backup.Type): + The backup type, which suggests the trigger + for the backup. + description (str): + User-provided description of the backup. + cluster_uid (str): + Output only. The system-generated UID of the + cluster which was used to create this resource. + cluster_name (str): + Required. The full resource name of the backup source + cluster (e.g., + projects/{project}/locations/{region}/clusters/{cluster_id}). + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation), if + true, indicates that the service is actively + updating the resource. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + encryption_config (google.cloud.alloydb_v1.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backup with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1.types.EncryptionInfo): + Output only. The encryption information for + the backup. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + size_bytes (int): + Output only. The size of the backup in bytes. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which after the backup is eligible + to be garbage collected. It is the duration specified by the + backup's retention policy, added to the backup's + create_time. + expiry_quantity (google.cloud.alloydb_v1.types.Backup.QuantityBasedExpiry): + Output only. The QuantityBasedExpiry of the + backup, specified by the backup's retention + policy. Once the expiry quantity is over + retention, the backup is eligible to be garbage + collected. + database_version (google.cloud.alloydb_v1.types.DatabaseVersion): + Output only. The database engine major + version of the cluster this backup was created + from. Any restored cluster created from this + backup will have the same database version. + """ + class State(proto.Enum): + r"""Backup State + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + READY (1): + The backup is ready. + CREATING (2): + The backup is creating. + FAILED (3): + The backup failed. + DELETING (4): + The backup is being deleted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + CREATING = 2 + FAILED = 3 + DELETING = 4 + + class Type(proto.Enum): + r"""Backup Type + + Values: + TYPE_UNSPECIFIED (0): + Backup Type is unknown. + ON_DEMAND (1): + ON_DEMAND backups that were triggered by the customer (e.g., + not AUTOMATED). + AUTOMATED (2): + AUTOMATED backups triggered by the automated + backups scheduler pursuant to an automated + backup policy. + CONTINUOUS (3): + CONTINUOUS backups triggered by the automated + backups scheduler due to a continuous backup + policy. + """ + TYPE_UNSPECIFIED = 0 + ON_DEMAND = 1 + AUTOMATED = 2 + CONTINUOUS = 3 + + class QuantityBasedExpiry(proto.Message): + r"""A backup's position in a quantity-based retention queue, of backups + with the same source cluster and type, with length, retention, + specified by the backup's retention policy. Once the position is + greater than the retention, the backup is eligible to be garbage + collected. + + Example: 5 backups from the same source cluster and type with a + quantity-based retention of 3 and denoted by backup_id (position, + retention). + + Safe: backup_5 (1, 3), backup_4, (2, 3), backup_3 (3, 3). Awaiting + garbage collection: backup_2 (4, 3), backup_1 (5, 3) + + Attributes: + retention_count (int): + Output only. The backup's position among its + backups with the same source cluster and type, + by descending chronological order create + time(i.e. newest first). + total_retention_count (int): + Output only. The length of the quantity-based + queue, specified by the backup's retention + policy. + """ + + retention_count: int = proto.Field( + proto.INT32, + number=1, + ) + total_retention_count: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + type_: Type = proto.Field( + proto.ENUM, + number=8, + enum=Type, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + cluster_uid: str = proto.Field( + proto.STRING, + number=18, + ) + cluster_name: str = proto.Field( + proto.STRING, + number=10, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=11, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='EncryptionInfo', + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=16, + ) + size_bytes: int = proto.Field( + proto.INT64, + number=17, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + expiry_quantity: QuantityBasedExpiry = proto.Field( + proto.MESSAGE, + number=20, + message=QuantityBasedExpiry, + ) + database_version: 'DatabaseVersion' = proto.Field( + proto.ENUM, + number=22, + enum='DatabaseVersion', + ) + + +class SupportedDatabaseFlag(proto.Message): + r"""SupportedDatabaseFlag gives general information about a database + flag, like type and allowed values. This is a static value that is + defined on the server side, and it cannot be modified by callers. To + set the Database flags on a particular Instance, a caller should + modify the Instance.database_flags field. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_restrictions (google.cloud.alloydb_v1.types.SupportedDatabaseFlag.StringRestrictions): + Restriction on STRING type value. + + This field is a member of `oneof`_ ``restrictions``. + integer_restrictions (google.cloud.alloydb_v1.types.SupportedDatabaseFlag.IntegerRestrictions): + Restriction on INTEGER type value. + + This field is a member of `oneof`_ ``restrictions``. + name (str): + The name of the flag resource, following Google Cloud + conventions, e.g.: + + - projects/{project}/locations/{location}/flags/{flag} This + field currently has no semantic meaning. + flag_name (str): + The name of the database flag, e.g. "max_allowed_packets". + The is a possibly key for the Instance.database_flags map + field. + value_type (google.cloud.alloydb_v1.types.SupportedDatabaseFlag.ValueType): + + accepts_multiple_values (bool): + Whether the database flag accepts multiple + values. If true, a comma-separated list of + stringified values may be specified. + supported_db_versions (MutableSequence[google.cloud.alloydb_v1.types.DatabaseVersion]): + Major database engine versions for which this + flag is supported. + requires_db_restart (bool): + Whether setting or updating this flag on an + Instance requires a database restart. If a flag + that requires database restart is set, the + backend will automatically restart the database + (making sure to satisfy any availability SLO's). + """ + class ValueType(proto.Enum): + r"""ValueType describes the semantic type of the value that the flag + accepts. Regardless of the ValueType, the Instance.database_flags + field accepts the stringified version of the value, i.e. "20" or + "3.14". + + Values: + VALUE_TYPE_UNSPECIFIED (0): + This is an unknown flag type. + STRING (1): + String type flag. + INTEGER (2): + Integer type flag. + FLOAT (3): + Float type flag. + NONE (4): + Denotes that the flag does not accept any + values. + """ + VALUE_TYPE_UNSPECIFIED = 0 + STRING = 1 + INTEGER = 2 + FLOAT = 3 + NONE = 4 + + class StringRestrictions(proto.Message): + r"""Restrictions on STRING type values + + Attributes: + allowed_values (MutableSequence[str]): + The list of allowed values, if bounded. This + field will be empty if there is a unbounded + number of allowed values. + """ + + allowed_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class IntegerRestrictions(proto.Message): + r"""Restrictions on INTEGER type values. + + Attributes: + min_value (google.protobuf.wrappers_pb2.Int64Value): + The minimum value that can be specified, if + applicable. + max_value (google.protobuf.wrappers_pb2.Int64Value): + The maximum value that can be specified, if + applicable. + """ + + min_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int64Value, + ) + max_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + + string_restrictions: StringRestrictions = proto.Field( + proto.MESSAGE, + number=7, + oneof='restrictions', + message=StringRestrictions, + ) + integer_restrictions: IntegerRestrictions = proto.Field( + proto.MESSAGE, + number=8, + oneof='restrictions', + message=IntegerRestrictions, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + flag_name: str = proto.Field( + proto.STRING, + number=2, + ) + value_type: ValueType = proto.Field( + proto.ENUM, + number=3, + enum=ValueType, + ) + accepts_multiple_values: bool = proto.Field( + proto.BOOL, + number=4, + ) + supported_db_versions: MutableSequence['DatabaseVersion'] = proto.RepeatedField( + proto.ENUM, + number=5, + enum='DatabaseVersion', + ) + requires_db_restart: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class User(proto.Message): + r"""Message describing User object. + + Attributes: + name (str): + Output only. Name of the resource in the form + of + projects/{project}/locations/{location}/cluster/{cluster}/users/{user}. + password (str): + Input only. Password for the user. + database_roles (MutableSequence[str]): + Optional. List of database roles this user + has. The database role strings are subject to + the PostgreSQL naming conventions. + user_type (google.cloud.alloydb_v1.types.User.UserType): + Optional. Type of this user. + """ + class UserType(proto.Enum): + r"""Enum that details the user type. + + Values: + USER_TYPE_UNSPECIFIED (0): + Unspecified user type. + ALLOYDB_BUILT_IN (1): + The default user type that authenticates via + password-based authentication. + ALLOYDB_IAM_USER (2): + Database user that can authenticate via + IAM-Based authentication. + """ + USER_TYPE_UNSPECIFIED = 0 + ALLOYDB_BUILT_IN = 1 + ALLOYDB_IAM_USER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + database_roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + user_type: UserType = proto.Field( + proto.ENUM, + number=5, + enum=UserType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/service.py b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/service.py new file mode 100644 index 000000000000..ac57427ab320 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/google/cloud/alloydb_v1/types/service.py @@ -0,0 +1,1980 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.alloydb_v1.types import resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1', + manifest={ + 'ListClustersRequest', + 'ListClustersResponse', + 'GetClusterRequest', + 'CreateSecondaryClusterRequest', + 'CreateClusterRequest', + 'UpdateClusterRequest', + 'DeleteClusterRequest', + 'PromoteClusterRequest', + 'RestoreClusterRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'CreateInstanceRequest', + 'CreateSecondaryInstanceRequest', + 'CreateInstanceRequests', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstanceStatus', + 'UpdateInstanceRequest', + 'DeleteInstanceRequest', + 'FailoverInstanceRequest', + 'InjectFaultRequest', + 'RestartInstanceRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'UpdateBackupRequest', + 'DeleteBackupRequest', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'OperationMetadata', + 'ListUsersRequest', + 'ListUsersResponse', + 'GetUserRequest', + 'CreateUserRequest', + 'UpdateUserRequest', + 'DeleteUserRequest', + }, +) + + +class ListClustersRequest(proto.Message): + r"""Message for requesting list of Clusters + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Cluster.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with the following format: + + - projects/{project}/locations/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListClustersResponse(proto.Message): + r"""Message for response to listing Clusters + + Attributes: + clusters (MutableSequence[google.cloud.alloydb_v1.types.Cluster]): + The list of Cluster + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + clusters: MutableSequence[resources.Cluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Cluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetClusterRequest(proto.Message): + r"""Message for getting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + view (google.cloud.alloydb_v1.types.ClusterView): + Optional. The view of the cluster to return. + Returns all default fields if not set. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.ClusterView = proto.Field( + proto.ENUM, + number=2, + enum=resources.ClusterView, + ) + + +class CreateSecondaryClusterRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object (the + secondary cluster). + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. Configuration of the requesting + object (the secondary cluster). + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class CreateClusterRequest(proto.Message): + r"""Message for creating a Cluster + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateClusterRequest(proto.Message): + r"""Message for updating a Cluster + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if cluster is + not found. In that case, a new cluster is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteClusterRequest(proto.Message): + r"""Message for deleting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + force (bool): + Optional. Whether to cascade delete child + instances for given cluster. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PromoteClusterRequest(proto.Message): + r"""Message for promoting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestoreClusterRequest(proto.Message): + r"""Message for restoring a Cluster from a backup or another + cluster at a given point in time. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1.types.BackupSource): + Backup source. + + This field is a member of `oneof`_ ``source``. + continuous_backup_source (google.cloud.alloydb_v1.types.ContinuousBackupSource): + ContinuousBackup source. Continuous backup + needs to be enabled in the source cluster for + this operation to succeed. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + import request. + """ + + backup_source: resources.BackupSource = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=resources.BackupSource, + ) + continuous_backup_source: resources.ContinuousBackupSource = proto.Field( + proto.MESSAGE, + number=8, + oneof='source', + message=resources.ContinuousBackupSource, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Instance.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with one of the following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1.types.Instance]): + The list of Instance + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Message for getting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + view (google.cloud.alloydb_v1.types.InstanceView): + The view of the instance to return. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.InstanceView = proto.Field( + proto.ENUM, + number=2, + enum=resources.InstanceView, + ) + + +class CreateInstanceRequest(proto.Message): + r"""Message for creating a Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateSecondaryInstanceRequest(proto.Message): + r"""Message for creating a Secondary Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateInstanceRequests(proto.Message): + r"""See usage below for notes. + + Attributes: + create_instance_requests (MutableSequence[google.cloud.alloydb_v1.types.CreateInstanceRequest]): + Required. Primary and read replica instances + to be created. This list should not be empty. + """ + + create_instance_requests: MutableSequence['CreateInstanceRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CreateInstanceRequest', + ) + + +class BatchCreateInstancesRequest(proto.Message): + r"""Message for creating a batch of instances under the specified + cluster. + + Attributes: + parent (str): + Required. The name of the parent resource. + requests (google.cloud.alloydb_v1.types.CreateInstanceRequests): + Required. Resources being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: 'CreateInstanceRequests' = proto.Field( + proto.MESSAGE, + number=2, + message='CreateInstanceRequests', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchCreateInstancesResponse(proto.Message): + r"""Message for creating batches of instances in a cluster. + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1.types.Instance]): + Created instances. + """ + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + + +class BatchCreateInstancesMetadata(proto.Message): + r"""Message for metadata that is specific to BatchCreateInstances API. + NEXT_ID: 3 + + Attributes: + instance_targets (MutableSequence[str]): + The instances being created in the API call. + Each string in this list is the server defined + resource path for target instances in the + request and for the format of each string, see + the comment on the Instance.name field. + instance_statuses (MutableMapping[str, google.cloud.alloydb_v1.types.BatchCreateInstanceStatus]): + A map representing state of the instances involved in the + BatchCreateInstances operation during the operation + execution. The instance state will be in STATE_UNSPECIFIED + state if the instance has not yet been picked up for + processing. The key of the map is the name of the instance + resource. For the format, see the comment on the + Instance.name field. + """ + + instance_targets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + instance_statuses: MutableMapping[str, 'BatchCreateInstanceStatus'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='BatchCreateInstanceStatus', + ) + + +class BatchCreateInstanceStatus(proto.Message): + r"""Message for current status of an instance in the + BatchCreateInstances operation. For example, lets say a + BatchCreateInstances workflow has 4 instances, Instance1 through + Instance4. Lets also assume that 2 instances succeeded but the third + failed to create and the 4th was never picked up for creation + because of failure of the previous one. Then, resulting states would + look something like: + + 1. Instance1 = ROLLED_BACK + 2. Instance2 = ROLLED_BACK + 3. Instance3 = FAILED + 4. Instance4 = FAILED + + However, while the operation is running, the instance might be in + other states including PENDING_CREATE, ACTIVE, DELETING and + CREATING. The states / do not get further updated once the operation + is done. + + Attributes: + state (google.cloud.alloydb_v1.types.BatchCreateInstanceStatus.State): + The current state of an instance involved in the batch + create operation. Once the operation is complete, the final + state of the instances in the LRO can be one of: + + 1. ACTIVE, indicating that instances were created + successfully + 2. FAILED, indicating that a particular instance failed + creation + 3. ROLLED_BACK indicating that although the instance was + created successfully, it had to be rolled back and + deleted due to failure in other steps of the workflow. + error_msg (str): + DEPRECATED - Use the error field instead. + Error, if any error occurred and is available, + during instance creation. + error (google.rpc.status_pb2.Status): + The RPC status of the instance creation + operation. This field will be present if an + error happened during the instance creation. + type_ (google.cloud.alloydb_v1.types.Instance.InstanceType): + + """ + class State(proto.Enum): + r"""State contains all valid instance states for the + BatchCreateInstances operation. This is mainly used for status + reporting through the LRO metadata. + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + PENDING_CREATE (1): + Instance is pending creation and has not yet + been picked up for processsing in the backend. + READY (2): + The instance is active and running. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + FAILED (5): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance or a batch of instances. + ROLLED_BACK (6): + The instance was created successfully, but + was rolled back and deleted due to some other + failure during BatchCreateInstances operation. + """ + STATE_UNSPECIFIED = 0 + PENDING_CREATE = 1 + READY = 2 + CREATING = 3 + DELETING = 4 + FAILED = 5 + ROLLED_BACK = 6 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + error_msg: str = proto.Field( + proto.STRING, + number=2, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + type_: resources.Instance.InstanceType = proto.Field( + proto.ENUM, + number=3, + enum=resources.Instance.InstanceType, + ) + + +class UpdateInstanceRequest(proto.Message): + r"""Message for updating a Instance + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + instance (google.cloud.alloydb_v1.types.Instance): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new instance is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Message for deleting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Instance. + If an etag is provided and does not match the + current etag of the Instance, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class FailoverInstanceRequest(proto.Message): + r"""Message for triggering failover on an Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + failover. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class InjectFaultRequest(proto.Message): + r"""Message for triggering fault injection on an instance + + Attributes: + fault_type (google.cloud.alloydb_v1.types.InjectFaultRequest.FaultType): + Required. The type of fault to be injected in + an instance. + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + fault injection. + """ + class FaultType(proto.Enum): + r"""FaultType contains all valid types of faults that can be + injected to an instance. + + Values: + FAULT_TYPE_UNSPECIFIED (0): + The fault type is unknown. + STOP_VM (1): + Stop the VM + """ + FAULT_TYPE_UNSPECIFIED = 0 + STOP_VM = 1 + + fault_type: FaultType = proto.Field( + proto.ENUM, + number=1, + enum=FaultType, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestartInstanceRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + restart. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Message for requesting list of Backups + + Attributes: + parent (str): + Required. Parent value for ListBackupsRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListBackupsResponse(proto.Message): + r"""Message for response to listing Backups + + Attributes: + backups (MutableSequence[google.cloud.alloydb_v1.types.Backup]): + The list of Backup + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence[resources.Backup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.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"""Message for getting a Backup + + Attributes: + name (str): + Required. Name of the resource + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Message for creating a Backup + + Attributes: + parent (str): + Required. Value for parent. + backup_id (str): + Required. ID of the requesting object. + backup (google.cloud.alloydb_v1.types.Backup): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateBackupRequest(proto.Message): + r"""Message for updating a Backup + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + backup (google.cloud.alloydb_v1.types.Backup): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new backup is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Message for deleting a Backup + + Attributes: + name (str): + Required. Name of the resource. For the + required format, see the comment on the + Backup.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + etag (str): + Optional. The current etag of the Backup. + If an etag is provided and does not match the + current etag of the Backup, deletion will be + blocked and an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSupportedDatabaseFlagsRequest(proto.Message): + r"""Message for listing the information about the supported + Database flags. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note that + we do not yet support region-specific flags. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSupportedDatabaseFlagsResponse(proto.Message): + r"""Message for response to listing SupportedDatabaseFlags. + + Attributes: + supported_database_flags (MutableSequence[google.cloud.alloydb_v1.types.SupportedDatabaseFlag]): + The list of SupportedDatabaseFlags. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + supported_database_flags: MutableSequence[resources.SupportedDatabaseFlag] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.SupportedDatabaseFlag, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + batch_create_instances_metadata (google.cloud.alloydb_v1.types.BatchCreateInstancesMetadata): + Output only. BatchCreateInstances related + metadata. + + This field is a member of `oneof`_ ``request_specific``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + 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. + """ + + batch_create_instances_metadata: 'BatchCreateInstancesMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='request_specific', + message='BatchCreateInstancesMetadata', + ) + 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 ListUsersRequest(proto.Message): + r"""Message for requesting list of Users + + Attributes: + parent (str): + Required. Parent value for ListUsersRequest + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListUsersResponse(proto.Message): + r"""Message for response to listing Users + + Attributes: + users (MutableSequence[google.cloud.alloydb_v1.types.User]): + The list of User + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence[resources.User] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.User, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetUserRequest(proto.Message): + r"""Message for getting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserRequest(proto.Message): + r"""Message for creating a User + + Attributes: + parent (str): + Required. Value for parent. + user_id (str): + Required. ID of the requesting object. + user (google.cloud.alloydb_v1.types.User): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=3, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateUserRequest(proto.Message): + r"""Message for updating a User + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + user (google.cloud.alloydb_v1.types.User): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. Allow missing fields in the update + mask. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=2, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteUserRequest(proto.Message): + r"""Message for deleting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/mypy.ini b/owl-bot-staging/google-cloud-alloydb/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1/noxfile.py b/owl-bot-staging/google-cloud-alloydb/v1/noxfile.py new file mode 100644 index 000000000000..dc7b703ce955 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/alloydb_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==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_async.py new file mode 100644 index 000000000000..fa0fdce77545 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1 + + +async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_sync.py new file mode 100644 index 000000000000..e6832b20c2cf --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_batch_create_instances_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1 + + +def sample_batch_create_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_async.py new file mode 100644 index 000000000000..12dc0695ae0f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +async def sample_create_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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 alloydb_v1_generated_AlloyDBAdmin_CreateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_sync.py new file mode 100644 index 000000000000..321152534f6a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_backup_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +def sample_create_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_async.py new file mode 100644 index 000000000000..bfc3e238e386 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1 + + +async def sample_create_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_sync.py new file mode 100644 index 000000000000..d53a82291c4a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1 + + +def sample_create_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_async.py new file mode 100644 index 000000000000..0e49b296d7b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1 + + +async def sample_create_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_sync.py new file mode 100644 index 000000000000..5ab9a2b346fd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1 + + +def sample_create_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_async.py new file mode 100644 index 000000000000..64d7950a847e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1 + + +async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_sync.py new file mode 100644 index 000000000000..34a37537a9e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1 + + +def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_async.py new file mode 100644 index 000000000000..0a1cf111dd17 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1 + + +async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_sync.py new file mode 100644 index 000000000000..48fc5adeb2e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_secondary_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1 + + +def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_async.py new file mode 100644 index 000000000000..4dfe3d2c2d0f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1 + + +async def sample_create_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_sync.py new file mode 100644 index 000000000000..5e97553ea0d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_create_user_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1 + + +def sample_create_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_CreateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_async.py new file mode 100644 index 000000000000..02ec2a5925db --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +async def sample_delete_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1_generated_AlloyDBAdmin_DeleteBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_sync.py new file mode 100644 index 000000000000..af72ed69ebca --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +def sample_delete_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1_generated_AlloyDBAdmin_DeleteBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_async.py new file mode 100644 index 000000000000..240279a24aa0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1 + + +async def sample_delete_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_sync.py new file mode 100644 index 000000000000..20fd6436d394 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1 + + +def sample_delete_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_async.py new file mode 100644 index 000000000000..e69ef7826761 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1 + + +async def sample_delete_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_sync.py new file mode 100644 index 000000000000..05f465d04975 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1 + + +def sample_delete_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_async.py new file mode 100644 index 000000000000..9267ff07d287 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1 + + +async def sample_delete_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_sync.py new file mode 100644 index 000000000000..a65608eddb92 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_delete_user_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1 + + +def sample_delete_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END alloydb_v1_generated_AlloyDBAdmin_DeleteUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_async.py new file mode 100644 index 000000000000..6dc7238c4420 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1 + + +async def sample_failover_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py new file mode 100644 index 000000000000..5378712384df --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1 + + +def sample_failover_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_async.py new file mode 100644 index 000000000000..224f69a8495b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +async def sample_get_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_sync.py new file mode 100644 index 000000000000..58df047b6a61 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +def sample_get_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_async.py new file mode 100644 index 000000000000..ef97e2289b85 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1 + + +async def sample_get_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py new file mode 100644 index 000000000000..691cf620dc8e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1 + + +def sample_get_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_async.py new file mode 100644 index 000000000000..190aad2e9732 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1 + + +async def sample_get_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_sync.py new file mode 100644 index 000000000000..6391a448b9fa --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1 + + +def sample_get_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_async.py new file mode 100644 index 000000000000..0d8afb7d8bb0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetUser_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 alloydb_v1 + + +async def sample_get_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_sync.py new file mode 100644 index 000000000000..1d30f73688cd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_user_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetUser_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 alloydb_v1 + + +def sample_get_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_async.py new file mode 100644 index 000000000000..d1c3c9725311 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1 + + +async def sample_inject_fault(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_InjectFault_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_sync.py new file mode 100644 index 000000000000..d157c3b88d0c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_inject_fault_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1 + + +def sample_inject_fault(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_InjectFault_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_async.py new file mode 100644 index 000000000000..c77c348fd4b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +async def sample_list_backups(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1_generated_AlloyDBAdmin_ListBackups_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_sync.py new file mode 100644 index 000000000000..83b0ddc54ba0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_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 alloydb_v1 + + +def sample_list_backups(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1_generated_AlloyDBAdmin_ListBackups_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_async.py new file mode 100644 index 000000000000..298c6568177e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1 + + +async def sample_list_clusters(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py new file mode 100644 index 000000000000..ad02335c26af --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1 + + +def sample_list_clusters(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_async.py new file mode 100644 index 000000000000..8f3d79e6fd66 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1 + + +async def sample_list_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_sync.py new file mode 100644 index 000000000000..73e43bcf3f3f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1 + + +def sample_list_instances(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_async.py new file mode 100644 index 000000000000..a2eaef35c025 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1 + + +async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_sync.py new file mode 100644 index 000000000000..34fbbe7965fb --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1 + + +def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_async.py new file mode 100644 index 000000000000..2d0f62be135b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1 + + +async def sample_list_users(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListUsers_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_sync.py new file mode 100644 index 000000000000..19344ff93c2f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_users_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1 + + +def sample_list_users(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListUsers_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_async.py new file mode 100644 index 000000000000..726df61c6237 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1 + + +async def sample_promote_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_sync.py new file mode 100644 index 000000000000..c8f111565a21 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_promote_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1 + + +def sample_promote_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_async.py new file mode 100644 index 000000000000..0459979393e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1 + + +async def sample_restart_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_RestartInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_sync.py new file mode 100644 index 000000000000..7e13fa24c835 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restart_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1 + + +def sample_restart_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_RestartInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_async.py new file mode 100644 index 000000000000..63ee7f57abee --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1 + + +async def sample_restore_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py new file mode 100644 index 000000000000..9add138b3856 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1 + + +def sample_restore_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_async.py new file mode 100644 index 000000000000..53dfd23b5fb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1 + + +async def sample_update_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_sync.py new file mode 100644 index 000000000000..ac8e5b4b8fc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_backup_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1 + + +def sample_update_backup(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_async.py new file mode 100644 index 000000000000..191388f70958 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1 + + +async def sample_update_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_sync.py new file mode 100644 index 000000000000..901373549882 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_cluster_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1 + + +def sample_update_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_async.py new file mode 100644 index 000000000000..e9f7b3e56577 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1 + + +async def sample_update_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_sync.py new file mode 100644 index 000000000000..7f89fc223230 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_instance_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1 + + +def sample_update_instance(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_async.py new file mode 100644 index 000000000000..7ba740cbd3ba --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1 + + +async def sample_update_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_sync.py new file mode 100644 index 000000000000..2eb18f2c60b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_update_user_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1 + + +def sample_update_user(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_UpdateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json new file mode 100644 index 000000000000..425997888ed8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json @@ -0,0 +1,4798 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.alloydb.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-alloydb", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1_generated_alloy_db_admin_batch_create_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_batch_create_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1_generated_alloy_db_admin_batch_create_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_BatchCreateInstances_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_batch_create_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1_generated_alloy_db_admin_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateBackup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1_generated_alloy_db_admin_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateBackup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1_generated_alloy_db_admin_create_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1_generated_alloy_db_admin_create_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1_generated_alloy_db_admin_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1_generated_alloy_db_admin_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_secondary_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1_generated_alloy_db_admin_create_secondary_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_secondary_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1_generated_alloy_db_admin_create_secondary_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateSecondaryInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_secondary_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1_generated_alloy_db_admin_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateUser_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1_generated_alloy_db_admin_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_CreateUser_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1_generated_alloy_db_admin_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1_generated_alloy_db_admin_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1_generated_alloy_db_admin_delete_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1_generated_alloy_db_admin_delete_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1_generated_alloy_db_admin_delete_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1_generated_alloy_db_admin_delete_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1_generated_alloy_db_admin_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1_generated_alloy_db_admin_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1_generated_alloy_db_admin_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1_generated_alloy_db_admin_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1_generated_alloy_db_admin_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteUser_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1_generated_alloy_db_admin_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_DeleteUser_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1_generated_alloy_db_admin_failover_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1_generated_alloy_db_admin_failover_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1_generated_alloy_db_admin_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1_generated_alloy_db_admin_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetClusterRequest" + }, + { + "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.alloydb_v1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1_generated_alloy_db_admin_get_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1_generated_alloy_db_admin_get_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetClusterRequest" + }, + { + "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.alloydb_v1.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetInstanceRequest" + }, + { + "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.alloydb_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1_generated_alloy_db_admin_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1_generated_alloy_db_admin_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetInstanceRequest" + }, + { + "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.alloydb_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1_generated_alloy_db_admin_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1_generated_alloy_db_admin_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetUserRequest" + }, + { + "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.alloydb_v1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1_generated_alloy_db_admin_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1_generated_alloy_db_admin_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetUserRequest" + }, + { + "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.alloydb_v1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1_generated_alloy_db_admin_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1_generated_alloy_db_admin_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1_generated_alloy_db_admin_inject_fault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1_generated_alloy_db_admin_inject_fault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1_generated_alloy_db_admin_inject_fault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1_generated_alloy_db_admin_inject_fault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1.services.alloy_db_admin.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1_generated_alloy_db_admin_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1.services.alloy_db_admin.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1_generated_alloy_db_admin_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_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": "alloydb_v1_generated_alloy_db_admin_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListClustersRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListClustersAsyncPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1_generated_alloy_db_admin_list_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1_generated_alloy_db_admin_list_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListClustersRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListClustersPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListInstancesRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1_generated_alloy_db_admin_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1_generated_alloy_db_admin_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListInstancesRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1_generated_alloy_db_admin_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1_generated_alloy_db_admin_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1_generated_alloy_db_admin_list_supported_database_flags_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListUsersRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1_generated_alloy_db_admin_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1_generated_alloy_db_admin_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListUsersRequest" + }, + { + "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.alloydb_v1.services.alloy_db_admin.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1_generated_alloy_db_admin_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1_generated_alloy_db_admin_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1_generated_alloy_db_admin_promote_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1_generated_alloy_db_admin_promote_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1_generated_alloy_db_admin_promote_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1_generated_alloy_db_admin_promote_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1_generated_alloy_db_admin_restart_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1_generated_alloy_db_admin_restart_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1_generated_alloy_db_admin_restart_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1_generated_alloy_db_admin_restart_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1_generated_alloy_db_admin_restore_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_restore_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_RestoreCluster_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1_generated_alloy_db_admin_update_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1_generated_alloy_db_admin_update_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1_generated_alloy_db_admin_update_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1_generated_alloy_db_admin_update_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1_generated_alloy_db_admin_update_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_update_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1_generated_alloy_db_admin_update_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateCluster_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_update_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1_generated_alloy_db_admin_update_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1_generated_alloy_db_admin_update_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1_generated_alloy_db_admin_update_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1_generated_alloy_db_admin_update_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1_generated_alloy_db_admin_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1_generated_alloy_db_admin_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_UpdateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_update_user_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1/scripts/fixup_alloydb_v1_keywords.py b/owl-bot-staging/google-cloud-alloydb/v1/scripts/fixup_alloydb_v1_keywords.py new file mode 100644 index 000000000000..c3c6a1d576f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/scripts/fixup_alloydb_v1_keywords.py @@ -0,0 +1,204 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class alloydbCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_instances': ('parent', 'requests', 'request_id', ), + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', 'validate_only', ), + 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_secondary_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_secondary_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_user': ('parent', 'user_id', 'user', 'request_id', 'validate_only', ), + 'delete_backup': ('name', 'request_id', 'validate_only', 'etag', ), + 'delete_cluster': ('name', 'request_id', 'etag', 'validate_only', 'force', ), + 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), + 'delete_user': ('name', 'request_id', 'validate_only', ), + 'failover_instance': ('name', 'request_id', 'validate_only', ), + 'get_backup': ('name', ), + 'get_cluster': ('name', 'view', ), + 'get_instance': ('name', 'view', ), + 'get_user': ('name', ), + 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_supported_database_flags': ('parent', 'page_size', 'page_token', ), + 'list_users': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'promote_cluster': ('name', 'request_id', 'etag', 'validate_only', ), + 'restart_instance': ('name', 'request_id', 'validate_only', ), + 'restore_cluster': ('parent', 'cluster_id', 'cluster', 'backup_source', 'continuous_backup_source', 'request_id', 'validate_only', ), + 'update_backup': ('backup', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_cluster': ('cluster', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_instance': ('instance', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_user': ('user', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + } + + 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=alloydbCallTransformer(), +): + """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 alloydb client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/setup.py b/owl-bot-staging/google-cloud-alloydb/v1/setup.py new file mode 100644 index 000000000000..4c8aa9156a9f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-alloydb' + + +description = "Google Cloud Alloydb API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/alloydb/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-alloydb" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2beecf99e0be --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-alloydb/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1/tests/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py new file mode 100644 index 000000000000..0048735ad4ed --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py @@ -0,0 +1,17474 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.alloydb_v1.services.alloy_db_admin import AlloyDBAdminAsyncClient +from google.cloud.alloydb_v1.services.alloy_db_admin import AlloyDBAdminClient +from google.cloud.alloydb_v1.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1.services.alloy_db_admin import transports +from google.cloud.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import service +from google.cloud.location import locations_pb2 +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 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +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.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_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 AlloyDBAdminClient._get_default_mtls_endpoint(None) is None + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AlloyDBAdminGrpcTransport, "grpc"), + (transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +def test_alloy_db_admin_client_get_transport_class(): + transport = AlloyDBAdminClient.get_transport_class() + available_transports = [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminRestTransport, + ] + assert transport in available_transports + + transport = AlloyDBAdminClient.get_transport_class("grpc") + assert transport == transports.AlloyDBAdminGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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(AlloyDBAdminClient, '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(AlloyDBAdminClient, '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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "true"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "false"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "false"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_alloy_db_admin_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", [ + AlloyDBAdminClient, AlloyDBAdminAsyncClient +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", None), +]) +def test_alloy_db_admin_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_alloy_db_admin_client_client_options_from_dict(): + with mock.patch('google.cloud.alloydb_v1.services.alloy_db_admin.transports.AlloyDBAdminGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_clusters), + '__call__') as call: + client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + +@pytest.mark.asyncio +async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=service.ListClustersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_clusters_async_from_dict(): + await test_list_clusters_async(request_type=dict) + + +def test_list_clusters_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = service.ListClustersResponse() + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_clusters_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_clusters_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_clusters( + 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_clusters_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_clusters_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_clusters( + 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_clusters_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) +def test_list_clusters_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clusters(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_clusters_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clusters(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Cluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_clusters_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + ) + response = client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +def test_get_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + +@pytest.mark.asyncio +async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=service.GetClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + )) + response = await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +@pytest.mark.asyncio +async def test_get_cluster_async_from_dict(): + await test_get_cluster_async(request_type=dict) + + +def test_get_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = resources.Cluster() + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + +@pytest.mark.asyncio +async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_cluster_async_from_dict(): + await test_create_cluster_async(request_type=dict) + + +def test_create_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + +@pytest.mark.asyncio +async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_cluster_async_from_dict(): + await test_update_cluster_async(request_type=dict) + + +def test_update_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + +@pytest.mark.asyncio +async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_cluster_async_from_dict(): + await test_delete_cluster_async(request_type=dict) + + +def test_delete_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_promote_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + client.promote_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + +@pytest.mark.asyncio +async def test_promote_cluster_async(transport: str = 'grpc_asyncio', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_promote_cluster_async_from_dict(): + await test_promote_cluster_async(request_type=dict) + + +def test_promote_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_promote_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_promote_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_promote_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.restore_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + +@pytest.mark.asyncio +async def test_restore_cluster_async(transport: str = 'grpc_asyncio', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_cluster_async_from_dict(): + await test_restore_cluster_async(request_type=dict) + + +def test_restore_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_restore_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_cluster), + '__call__') as call: + client.create_secondary_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__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_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async_from_dict(): + await test_create_secondary_cluster_async(request_type=dict) + + +def test_create_secondary_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_secondary_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instances), + '__call__') as call: + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=service.ListInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = service.ListInstancesResponse() + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instances_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + 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_instances_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + 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_instances_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) +def test_list_instances_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Instance) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +def test_get_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=service.GetInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = resources.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.create_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + +@pytest.mark.asyncio +async def test_create_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_instance), + '__call__') as call: + client.create_secondary_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + +@pytest.mark.asyncio +async def test_create_secondary_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__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_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_instance_async_from_dict(): + await test_create_secondary_instance_async(request_type=dict) + + +def test_create_secondary_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_secondary_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_create_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + client.batch_create_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + +@pytest.mark.asyncio +async def test_batch_create_instances_async(transport: str = 'grpc_asyncio', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__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.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_create_instances_async_from_dict(): + await test_batch_create_instances_async(request_type=dict) + + +def test_batch_create_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.update_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + +@pytest.mark.asyncio +async def test_update_instance_async(transport: str = 'grpc_asyncio', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_instance_async_from_dict(): + await test_update_instance_async(request_type=dict) + + +def test_update_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +def test_update_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + +@pytest.mark.asyncio +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_failover_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + client.failover_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + +@pytest.mark.asyncio +async def test_failover_instance_async(transport: str = 'grpc_asyncio', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_failover_instance_async_from_dict(): + await test_failover_instance_async(request_type=dict) + + +def test_failover_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_failover_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_failover_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_failover_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_inject_fault_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + client.inject_fault() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + +@pytest.mark.asyncio +async def test_inject_fault_async(transport: str = 'grpc_asyncio', request_type=service.InjectFaultRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_inject_fault_async_from_dict(): + await test_inject_fault_async(request_type=dict) + + +def test_inject_fault_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_inject_fault_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_inject_fault_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_inject_fault_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + +@pytest.mark.asyncio +async def test_inject_fault_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_inject_fault_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restart_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + client.restart_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + +@pytest.mark.asyncio +async def test_restart_instance_async(transport: str = 'grpc_asyncio', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restart_instance_async_from_dict(): + await test_restart_instance_async(request_type=dict) + + +def test_restart_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_restart_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_restart_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_restart_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = service.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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=service.ListBackupsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(service.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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(service.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 = AlloyDBAdminClient( + 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 = service.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 = AlloyDBAdminClient( + credentials=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( + service.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = service.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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 = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_backups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +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 = AlloyDBAdminClient( + credentials=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] == service.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=service.GetBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + )) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +@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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(resources.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 = AlloyDBAdminClient( + 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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = resources.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=service.CreateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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=resources.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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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=resources.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_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] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_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 = AlloyDBAdminClient( + credentials=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_backup), + '__call__') as call: + client.update_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + +@pytest.mark.asyncio +async def test_update_backup_async(transport: str = 'grpc_asyncio', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_backup_async_from_dict(): + await test_update_backup_async(request_type=dict) + + +def test_update_backup_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_backup_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +def test_update_backup_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=service.DeleteBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=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( + service.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_supported_database_flags), + '__call__') as call: + client.list_supported_database_flags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async(transport: str = 'grpc_asyncio', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_from_dict(): + await test_list_supported_database_flags_async(request_type=dict) + + +def test_list_supported_database_flags_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = service.ListSupportedDatabaseFlagsResponse() + client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_supported_database_flags_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_supported_database_flags_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_supported_database_flags( + 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_supported_database_flags_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_supported_database_flags_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_supported_database_flags( + 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_supported_database_flags_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_supported_database_flags(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) +def test_list_supported_database_flags_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_supported_database_flags(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_supported_database_flags_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_supported_database_flags(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_supported_database_flags(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.ListUsersRequest, + dict, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_users), + '__call__') as call: + client.list_users() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + +@pytest.mark.asyncio +async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=service.ListUsersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) + + +def test_list_users_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = service.ListUsersResponse() + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_users_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_users_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + 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_users_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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_users_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_users(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetUserRequest, + dict, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.get_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + +@pytest.mark.asyncio +async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=service.GetUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + + +def test_get_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = resources.User() + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.create_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + +@pytest.mark.asyncio +async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=service.CreateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) + + +def test_create_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = resources.User() + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.update_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + +@pytest.mark.asyncio +async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=service.UpdateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + + +def test_update_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = resources.User() + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +def test_update_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.delete_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + +@pytest.mark.asyncio +async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=service.DeleteUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + + +def test_delete_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListClustersResponse( + 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 = service.ListClustersResponse.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_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_clusters._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_clusters._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListClustersResponse.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_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_clusters._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_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_clusters") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json(service.ListClustersResponse()) + + request = service.ListClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request(transport: str = 'rest', request_type=service.ListClustersRequest): + client = AlloyDBAdminClient( + 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_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + + # 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 = service.ListClustersResponse.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_clusters(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_list_clusters_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.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_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) + + pages = list(client.list_clusters(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", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.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_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Cluster.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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + + request = service.GetClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Cluster() + + client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request(transport: str = 'rest', request_type=service.GetClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/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 = resources.Cluster.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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_get_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_cluster(request) + + +def test_create_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_create_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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.update_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_cluster_rest_bad_request(transport: str = 'rest', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster(**mock_args) + + # Establish that the underlying call 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/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_update_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request(transport: str = 'rest', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_delete_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +def test_delete_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_promote_cluster_rest_required_fields(request_type=service.PromoteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).promote_cluster._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()).promote_cluster._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 = AlloyDBAdminClient( + 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.promote_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_promote_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_promote_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_promote_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.PromoteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.promote_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_promote_cluster_rest_bad_request(transport: str = 'rest', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + +def test_promote_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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.promote_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}:promote" % client.transport._host, args[1]) + + +def test_promote_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +def test_promote_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster_rest(request_type): + client = AlloyDBAdminClient( + 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 = 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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_cluster_rest_required_fields(request_type=service.RestoreClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restore_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestoreClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_cluster_rest_bad_request(transport: str = 'rest', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminClient( + 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.restore_cluster(request) + + +def test_restore_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_secondary_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_cluster_rest_required_fields(request_type=service.CreateSecondaryClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_secondary_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryClusterRequest.pb(service.CreateSecondaryClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_secondary_cluster(request) + + +def test_create_secondary_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_secondary_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_secondary_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse( + 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 = service.ListInstancesResponse.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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instances._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_instances._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListInstancesResponse.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_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_instances._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_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListInstancesResponse.to_json(service.ListInstancesResponse()) + + request = service.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request(transport: str = 'rest', request_type=service.ListInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_instances(request) + + +def test_list_instances_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse.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_instances(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_list_instances_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.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/clusters/sample3'} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) + + pages = list(client.list_instances(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", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Instance.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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Instance.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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Instance.to_json(resources.Instance()) + + request = service.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=service.GetInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_get_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance.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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_instance_rest_required_fields(request_type=service.CreateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + +def test_create_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_create_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_secondary_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_instance_rest_required_fields(request_type=service.CreateSecondaryInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_secondary_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryInstanceRequest.pb(service.CreateSecondaryInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_secondary_instance(request) + + +def test_create_secondary_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_secondary_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_secondary_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}}}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and 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.batch_create_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_create_instances_rest_required_fields(request_type=service.BatchCreateInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).batch_create_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + 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.batch_create_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_batch_create_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.BatchCreateInstancesRequest.pb(service.BatchCreateInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.BatchCreateInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_create_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_instances_rest_bad_request(transport: str = 'rest', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}}}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_instances(request) + + +def test_batch_create_instances_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_instance_rest_required_fields(request_type=service.UpdateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request(transport: str = 'rest', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + +def test_update_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + instance=resources.Instance(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_instance(**mock_args) + + # Establish that the underlying call 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_update_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_instance_rest_required_fields(request_type=service.DeleteInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request(transport: str = 'rest', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_delete_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_delete_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +def test_delete_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_failover_instance_rest_required_fields(request_type=service.FailoverInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).failover_instance._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()).failover_instance._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 = AlloyDBAdminClient( + 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.failover_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_failover_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_failover_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_failover_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_failover_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FailoverInstanceRequest.pb(service.FailoverInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.FailoverInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.failover_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_failover_instance_rest_bad_request(transport: str = 'rest', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + +def test_failover_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.failover_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:failover" % client.transport._host, args[1]) + + +def test_failover_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +def test_failover_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).inject_fault._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()).inject_fault._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 = AlloyDBAdminClient( + 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.inject_fault(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_inject_fault_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.inject_fault._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("faultType", "name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_inject_fault_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_inject_fault") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_inject_fault") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.InjectFaultRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.inject_fault(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_inject_fault_rest_bad_request(transport: str = 'rest', request_type=service.InjectFaultRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + +def test_inject_fault_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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.inject_fault(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1]) + + +def test_inject_fault_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +def test_inject_fault_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restart_instance_rest_required_fields(request_type=service.RestartInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).restart_instance._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()).restart_instance._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 = AlloyDBAdminClient( + 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.restart_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restart_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restart_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restart_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restart_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restart_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestartInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restart_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restart_instance_rest_bad_request(transport: str = 'rest', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + +def test_restart_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.restart_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:restart" % client.transport._host, args[1]) + + +def test_restart_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +def test_restart_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.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 = service.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=service.ListBackupsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.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 = service.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListBackupsRequest.pb(service.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 = service.ListBackupsResponse.to_json(service.ListBackupsResponse()) + + request = service.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.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=service.ListBackupsRequest): + client = AlloyDBAdminClient( + 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_backups(request) + + +def test_list_backups_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListBackupsResponse() + + # 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 = service.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/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.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'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.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", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.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, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.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 = resources.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetBackupRequest.pb(service.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 = resources.Backup.to_json(resources.Backup()) + + request = service.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.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=service.GetBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/backups/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 = resources.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/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_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=service.CreateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", "validateOnly", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateBackupRequest.pb(service.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 = service.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=service.CreateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + +def test_create_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + backup=resources.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/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_backup._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_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_backup_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_backup_rest_bad_request(transport: str = 'rest', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + +def test_update_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + backup=resources.Backup(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_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/{backup.name=projects/*/locations/*/backups/*}" % client.transport._host, args[1]) + + +def test_update_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_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=service.DeleteBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteBackupRequest.pb(service.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 = service.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=service.DeleteBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_delete_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/backups/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_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/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_rest_required_fields(request_type=service.ListSupportedDatabaseFlagsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_supported_database_flags._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_supported_database_flags._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_supported_database_flags_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_supported_database_flags._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_supported_database_flags_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListSupportedDatabaseFlagsRequest.pb(service.ListSupportedDatabaseFlagsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json(service.ListSupportedDatabaseFlagsResponse()) + + request = service.ListSupportedDatabaseFlagsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListSupportedDatabaseFlagsResponse() + + client.list_supported_database_flags(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_supported_database_flags_rest_bad_request(transport: str = 'rest', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminClient( + 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_supported_database_flags(request) + + +def test_list_supported_database_flags_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + + # 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(**mock_args) + + # Establish that the underlying call 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/*}/supportedDatabaseFlags" % client.transport._host, args[1]) + + +def test_list_supported_database_flags_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) + + pages = list(client.list_supported_database_flags(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", [ + service.ListUsersRequest, + dict, +]) +def test_list_users_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse( + 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 = service.ListUsersResponse.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_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_users._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_users._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListUsersResponse.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_users(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_users_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_users._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_users_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListUsersRequest.pb(service.ListUsersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListUsersResponse.to_json(service.ListUsersResponse()) + + request = service.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListUsersResponse() + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_users_rest_bad_request(transport: str = 'rest', request_type=service.ListUsersRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_users(request) + + +def test_list_users_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse.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_users(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_list_users_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListUsersResponse.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/clusters/sample3'} + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) + + pages = list(client.list_users(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", [ + service.GetUserRequest, + dict, +]) +def test_get_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.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_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_rest_required_fields(request_type=service.GetUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.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_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetUserRequest.pb(service.GetUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_rest_bad_request(transport: str = 'rest', request_type=service.GetUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_get_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User.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_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.GetUserRequest(), + name='name_value', + ) + + +def test_get_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_rest_required_fields(request_type=service.CreateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_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 "userId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userId"] = 'user_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._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", "user_id", "validate_only", )) + 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 "userId" in jsonified_request + assert jsonified_request["userId"] == 'user_id_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_user(request) + + expected_params = [ + ( + "userId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "userId", "validateOnly", )) & set(("parent", "userId", "user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateUserRequest.pb(service.CreateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_rest_bad_request(transport: str = 'rest', request_type=service.CreateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_create_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +def test_create_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateUserRequest.pb(service.UpdateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_rest_bad_request(transport: str = 'rest', request_type=service.UpdateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_update_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_user(**mock_args) + + # Establish that the underlying call 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/{user.name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_update_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = 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_user(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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", "validate_only", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = service.DeleteUserRequest.pb(service.DeleteUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = service.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_user_rest_bad_request(transport: str = 'rest', request_type=service.DeleteUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_delete_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +def test_delete_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AlloyDBAdminClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, +]) +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 = AlloyDBAdminClient.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AlloyDBAdminGrpcTransport, + ) + +def test_alloy_db_admin_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_alloy_db_admin_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.alloydb_v1.services.alloy_db_admin.transports.AlloyDBAdminTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_clusters', + 'get_cluster', + 'create_cluster', + 'update_cluster', + 'delete_cluster', + 'promote_cluster', + 'restore_cluster', + 'create_secondary_cluster', + 'list_instances', + 'get_instance', + 'create_instance', + 'create_secondary_instance', + 'batch_create_instances', + 'update_instance', + 'delete_instance', + 'failover_instance', + 'inject_fault', + 'restart_instance', + 'list_backups', + 'get_backup', + 'create_backup', + 'update_backup', + 'delete_backup', + 'list_supported_database_flags', + 'list_users', + 'get_user', + 'create_user', + 'update_user', + 'delete_user', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # 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_alloy_db_admin_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.alloydb_v1.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport( + 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_alloy_db_admin_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.alloydb_v1.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport() + adc.assert_called_once() + + +def test_alloy_db_admin_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) + AlloyDBAdminClient() + 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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, grpc_helpers), + (transports.AlloyDBAdminGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_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.AlloyDBAdminRestTransport ( + 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_alloy_db_admin_rest_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_host_no_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_alloy_db_admin_host_with_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_alloy_db_admin_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AlloyDBAdminClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AlloyDBAdminClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.promote_cluster._session + session2 = client2.transport.promote_cluster._session + assert session1 != session2 + session1 = client1.transport.restore_cluster._session + session2 = client2.transport.restore_cluster._session + assert session1 != session2 + session1 = client1.transport.create_secondary_cluster._session + session2 = client2.transport.create_secondary_cluster._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.create_secondary_instance._session + session2 = client2.transport.create_secondary_instance._session + assert session1 != session2 + session1 = client1.transport.batch_create_instances._session + session2 = client2.transport.batch_create_instances._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.failover_instance._session + session2 = client2.transport.failover_instance._session + assert session1 != session2 + session1 = client1.transport.inject_fault._session + session2 = client2.transport.inject_fault._session + assert session1 != session2 + session1 = client1.transport.restart_instance._session + session2 = client2.transport.restart_instance._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.update_backup._session + session2 = client2.transport.update_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.list_supported_database_flags._session + session2 = client2.transport.list_supported_database_flags._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 +def test_alloy_db_admin_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcTransport( + 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_alloy_db_admin_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + 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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_grpc_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_grpc_lro_async_client(): + client = AlloyDBAdminAsyncClient( + 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" + backup = "whelk" + expected = "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, backup=backup, ) + actual = AlloyDBAdminClient.backup_path(project, location, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "octopus", + "location": "oyster", + "backup": "nudibranch", + } + path = AlloyDBAdminClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_backup_path(path) + assert expected == actual + +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = AlloyDBAdminClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = AlloyDBAdminClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_cluster_path(path) + assert expected == actual + +def test_crypto_key_version_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + crypto_key_version = "oyster" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = AlloyDBAdminClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "key_ring": "mussel", + "crypto_key": "winkle", + "crypto_key_version": "nautilus", + } + path = AlloyDBAdminClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_crypto_key_version_path(path) + assert expected == actual + +def test_instance_path(): + project = "scallop" + location = "abalone" + cluster = "squid" + instance = "clam" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + actual = AlloyDBAdminClient.instance_path(project, location, cluster, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "whelk", + "location": "octopus", + "cluster": "oyster", + "instance": "nudibranch", + } + path = AlloyDBAdminClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_instance_path(path) + assert expected == actual + +def test_network_path(): + project = "cuttlefish" + network = "mussel" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = AlloyDBAdminClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "winkle", + "network": "nautilus", + } + path = AlloyDBAdminClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_network_path(path) + assert expected == actual + +def test_supported_database_flag_path(): + project = "scallop" + location = "abalone" + flag = "squid" + expected = "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + actual = AlloyDBAdminClient.supported_database_flag_path(project, location, flag) + assert expected == actual + + +def test_parse_supported_database_flag_path(): + expected = { + "project": "clam", + "location": "whelk", + "flag": "octopus", + } + path = AlloyDBAdminClient.supported_database_flag_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_supported_database_flag_path(path) + assert expected == actual + +def test_user_path(): + project = "oyster" + location = "nudibranch" + cluster = "cuttlefish" + user = "mussel" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + actual = AlloyDBAdminClient.user_path(project, location, cluster, user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "cluster": "scallop", + "user": "abalone", + } + path = AlloyDBAdminClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AlloyDBAdminClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AlloyDBAdminClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AlloyDBAdminClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AlloyDBAdminClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AlloyDBAdminClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AlloyDBAdminClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AlloyDBAdminClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AlloyDBAdminClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AlloyDBAdminClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AlloyDBAdminClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.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.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + transport_class = AlloyDBAdminClient.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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport), +]) +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/google-cloud-alloydb/v1alpha/.coveragerc b/owl-bot-staging/google-cloud-alloydb/v1alpha/.coveragerc new file mode 100644 index 000000000000..307a1b7e14a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/alloydb/__init__.py + google/cloud/alloydb/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/.flake8 b/owl-bot-staging/google-cloud-alloydb/v1alpha/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/MANIFEST.in b/owl-bot-staging/google-cloud-alloydb/v1alpha/MANIFEST.in new file mode 100644 index 000000000000..0100e34da6d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/alloydb *.py +recursive-include google/cloud/alloydb_v1alpha *.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/README.rst b/owl-bot-staging/google-cloud-alloydb/v1alpha/README.rst new file mode 100644 index 000000000000..6a459d0a64f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Alloydb 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 Alloydb API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/alloy_db_admin.rst b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/alloy_db_admin.rst new file mode 100644 index 000000000000..15e3c4a2f15b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/alloy_db_admin.rst @@ -0,0 +1,10 @@ +AlloyDBAdmin +------------------------------ + +.. automodule:: google.cloud.alloydb_v1alpha.services.alloy_db_admin + :members: + :inherited-members: + +.. automodule:: google.cloud.alloydb_v1alpha.services.alloy_db_admin.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/services.rst b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/services.rst new file mode 100644 index 000000000000..51612828ca6b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Alloydb v1alpha API +============================================= +.. toctree:: + :maxdepth: 2 + + alloy_db_admin diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/types.rst b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/types.rst new file mode 100644 index 000000000000..2b74c1903ffc --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/alloydb_v1alpha/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Alloydb v1alpha API +========================================== + +.. automodule:: google.cloud.alloydb_v1alpha.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/conf.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/conf.py new file mode 100644 index 000000000000..16113c8bdd60 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-alloydb 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-alloydb" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-alloydb-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-alloydb.tex", + u"google-cloud-alloydb 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-alloydb", + u"Google Cloud Alloydb 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-alloydb", + u"google-cloud-alloydb Documentation", + author, + "google-cloud-alloydb", + "GAPIC library for Google Cloud Alloydb API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/index.rst b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/index.rst new file mode 100644 index 000000000000..6aae27dfa708 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + alloydb_v1alpha/services + alloydb_v1alpha/types diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/__init__.py new file mode 100644 index 000000000000..ce97840d4cdf --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/__init__.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.alloydb_v1alpha.services.alloy_db_admin.client import AlloyDBAdminClient +from google.cloud.alloydb_v1alpha.services.alloy_db_admin.async_client import AlloyDBAdminAsyncClient + +from google.cloud.alloydb_v1alpha.types.resources import AutomatedBackupPolicy +from google.cloud.alloydb_v1alpha.types.resources import Backup +from google.cloud.alloydb_v1alpha.types.resources import BackupSource +from google.cloud.alloydb_v1alpha.types.resources import Cluster +from google.cloud.alloydb_v1alpha.types.resources import ConnectionInfo +from google.cloud.alloydb_v1alpha.types.resources import ContinuousBackupConfig +from google.cloud.alloydb_v1alpha.types.resources import ContinuousBackupInfo +from google.cloud.alloydb_v1alpha.types.resources import ContinuousBackupSource +from google.cloud.alloydb_v1alpha.types.resources import EncryptionConfig +from google.cloud.alloydb_v1alpha.types.resources import EncryptionInfo +from google.cloud.alloydb_v1alpha.types.resources import Instance +from google.cloud.alloydb_v1alpha.types.resources import MigrationSource +from google.cloud.alloydb_v1alpha.types.resources import SslConfig +from google.cloud.alloydb_v1alpha.types.resources import SupportedDatabaseFlag +from google.cloud.alloydb_v1alpha.types.resources import User +from google.cloud.alloydb_v1alpha.types.resources import UserPassword +from google.cloud.alloydb_v1alpha.types.resources import ClusterView +from google.cloud.alloydb_v1alpha.types.resources import DatabaseVersion +from google.cloud.alloydb_v1alpha.types.resources import InstanceView +from google.cloud.alloydb_v1alpha.types.service import BatchCreateInstancesMetadata +from google.cloud.alloydb_v1alpha.types.service import BatchCreateInstancesRequest +from google.cloud.alloydb_v1alpha.types.service import BatchCreateInstancesResponse +from google.cloud.alloydb_v1alpha.types.service import BatchCreateInstanceStatus +from google.cloud.alloydb_v1alpha.types.service import CreateBackupRequest +from google.cloud.alloydb_v1alpha.types.service import CreateClusterRequest +from google.cloud.alloydb_v1alpha.types.service import CreateInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import CreateInstanceRequests +from google.cloud.alloydb_v1alpha.types.service import CreateSecondaryClusterRequest +from google.cloud.alloydb_v1alpha.types.service import CreateSecondaryInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import CreateUserRequest +from google.cloud.alloydb_v1alpha.types.service import DeleteBackupRequest +from google.cloud.alloydb_v1alpha.types.service import DeleteClusterRequest +from google.cloud.alloydb_v1alpha.types.service import DeleteInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import DeleteUserRequest +from google.cloud.alloydb_v1alpha.types.service import FailoverInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import GenerateClientCertificateRequest +from google.cloud.alloydb_v1alpha.types.service import GenerateClientCertificateResponse +from google.cloud.alloydb_v1alpha.types.service import GetBackupRequest +from google.cloud.alloydb_v1alpha.types.service import GetClusterRequest +from google.cloud.alloydb_v1alpha.types.service import GetConnectionInfoRequest +from google.cloud.alloydb_v1alpha.types.service import GetInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import GetUserRequest +from google.cloud.alloydb_v1alpha.types.service import InjectFaultRequest +from google.cloud.alloydb_v1alpha.types.service import ListBackupsRequest +from google.cloud.alloydb_v1alpha.types.service import ListBackupsResponse +from google.cloud.alloydb_v1alpha.types.service import ListClustersRequest +from google.cloud.alloydb_v1alpha.types.service import ListClustersResponse +from google.cloud.alloydb_v1alpha.types.service import ListInstancesRequest +from google.cloud.alloydb_v1alpha.types.service import ListInstancesResponse +from google.cloud.alloydb_v1alpha.types.service import ListSupportedDatabaseFlagsRequest +from google.cloud.alloydb_v1alpha.types.service import ListSupportedDatabaseFlagsResponse +from google.cloud.alloydb_v1alpha.types.service import ListUsersRequest +from google.cloud.alloydb_v1alpha.types.service import ListUsersResponse +from google.cloud.alloydb_v1alpha.types.service import OperationMetadata +from google.cloud.alloydb_v1alpha.types.service import PromoteClusterRequest +from google.cloud.alloydb_v1alpha.types.service import RestartInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import RestoreClusterRequest +from google.cloud.alloydb_v1alpha.types.service import UpdateBackupRequest +from google.cloud.alloydb_v1alpha.types.service import UpdateClusterRequest +from google.cloud.alloydb_v1alpha.types.service import UpdateInstanceRequest +from google.cloud.alloydb_v1alpha.types.service import UpdateUserRequest + +__all__ = ('AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ConnectionInfo', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetConnectionInfoRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/py.typed b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/__init__.py new file mode 100644 index 000000000000..c920cc935bbc --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/__init__.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb_v1alpha import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.alloy_db_admin import AlloyDBAdminClient +from .services.alloy_db_admin import AlloyDBAdminAsyncClient + +from .types.resources import AutomatedBackupPolicy +from .types.resources import Backup +from .types.resources import BackupSource +from .types.resources import Cluster +from .types.resources import ConnectionInfo +from .types.resources import ContinuousBackupConfig +from .types.resources import ContinuousBackupInfo +from .types.resources import ContinuousBackupSource +from .types.resources import EncryptionConfig +from .types.resources import EncryptionInfo +from .types.resources import Instance +from .types.resources import MigrationSource +from .types.resources import SslConfig +from .types.resources import SupportedDatabaseFlag +from .types.resources import User +from .types.resources import UserPassword +from .types.resources import ClusterView +from .types.resources import DatabaseVersion +from .types.resources import InstanceView +from .types.service import BatchCreateInstancesMetadata +from .types.service import BatchCreateInstancesRequest +from .types.service import BatchCreateInstancesResponse +from .types.service import BatchCreateInstanceStatus +from .types.service import CreateBackupRequest +from .types.service import CreateClusterRequest +from .types.service import CreateInstanceRequest +from .types.service import CreateInstanceRequests +from .types.service import CreateSecondaryClusterRequest +from .types.service import CreateSecondaryInstanceRequest +from .types.service import CreateUserRequest +from .types.service import DeleteBackupRequest +from .types.service import DeleteClusterRequest +from .types.service import DeleteInstanceRequest +from .types.service import DeleteUserRequest +from .types.service import FailoverInstanceRequest +from .types.service import GenerateClientCertificateRequest +from .types.service import GenerateClientCertificateResponse +from .types.service import GetBackupRequest +from .types.service import GetClusterRequest +from .types.service import GetConnectionInfoRequest +from .types.service import GetInstanceRequest +from .types.service import GetUserRequest +from .types.service import InjectFaultRequest +from .types.service import ListBackupsRequest +from .types.service import ListBackupsResponse +from .types.service import ListClustersRequest +from .types.service import ListClustersResponse +from .types.service import ListInstancesRequest +from .types.service import ListInstancesResponse +from .types.service import ListSupportedDatabaseFlagsRequest +from .types.service import ListSupportedDatabaseFlagsResponse +from .types.service import ListUsersRequest +from .types.service import ListUsersResponse +from .types.service import OperationMetadata +from .types.service import PromoteClusterRequest +from .types.service import RestartInstanceRequest +from .types.service import RestoreClusterRequest +from .types.service import UpdateBackupRequest +from .types.service import UpdateClusterRequest +from .types.service import UpdateInstanceRequest +from .types.service import UpdateUserRequest + +__all__ = ( + 'AlloyDBAdminAsyncClient', +'AlloyDBAdminClient', +'AutomatedBackupPolicy', +'Backup', +'BackupSource', +'BatchCreateInstanceStatus', +'BatchCreateInstancesMetadata', +'BatchCreateInstancesRequest', +'BatchCreateInstancesResponse', +'Cluster', +'ClusterView', +'ConnectionInfo', +'ContinuousBackupConfig', +'ContinuousBackupInfo', +'ContinuousBackupSource', +'CreateBackupRequest', +'CreateClusterRequest', +'CreateInstanceRequest', +'CreateInstanceRequests', +'CreateSecondaryClusterRequest', +'CreateSecondaryInstanceRequest', +'CreateUserRequest', +'DatabaseVersion', +'DeleteBackupRequest', +'DeleteClusterRequest', +'DeleteInstanceRequest', +'DeleteUserRequest', +'EncryptionConfig', +'EncryptionInfo', +'FailoverInstanceRequest', +'GenerateClientCertificateRequest', +'GenerateClientCertificateResponse', +'GetBackupRequest', +'GetClusterRequest', +'GetConnectionInfoRequest', +'GetInstanceRequest', +'GetUserRequest', +'InjectFaultRequest', +'Instance', +'InstanceView', +'ListBackupsRequest', +'ListBackupsResponse', +'ListClustersRequest', +'ListClustersResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListSupportedDatabaseFlagsRequest', +'ListSupportedDatabaseFlagsResponse', +'ListUsersRequest', +'ListUsersResponse', +'MigrationSource', +'OperationMetadata', +'PromoteClusterRequest', +'RestartInstanceRequest', +'RestoreClusterRequest', +'SslConfig', +'SupportedDatabaseFlag', +'UpdateBackupRequest', +'UpdateClusterRequest', +'UpdateInstanceRequest', +'UpdateUserRequest', +'User', +'UserPassword', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_metadata.json b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_metadata.json new file mode 100644 index 000000000000..10300b9955c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_metadata.json @@ -0,0 +1,493 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.alloydb_v1alpha", + "protoPackage": "google.cloud.alloydb.v1alpha", + "schema": "1.0", + "services": { + "AlloyDBAdmin": { + "clients": { + "grpc": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlloyDBAdminAsyncClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "rest": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/py.typed b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/__init__.py new file mode 100644 index 000000000000..364ae3da06ba --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AlloyDBAdminClient +from .async_client import AlloyDBAdminAsyncClient + +__all__ = ( + 'AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/async_client.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/async_client.py new file mode 100644 index 000000000000..20b9c24917a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/async_client.py @@ -0,0 +1,4279 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.alloydb_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.alloydb_v1alpha.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .client import AlloyDBAdminClient + + +class AlloyDBAdminAsyncClient: + """Service describing handlers for resources""" + + _client: AlloyDBAdminClient + + DEFAULT_ENDPOINT = AlloyDBAdminClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AlloyDBAdminClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(AlloyDBAdminClient.backup_path) + parse_backup_path = staticmethod(AlloyDBAdminClient.parse_backup_path) + cluster_path = staticmethod(AlloyDBAdminClient.cluster_path) + parse_cluster_path = staticmethod(AlloyDBAdminClient.parse_cluster_path) + connection_info_path = staticmethod(AlloyDBAdminClient.connection_info_path) + parse_connection_info_path = staticmethod(AlloyDBAdminClient.parse_connection_info_path) + crypto_key_version_path = staticmethod(AlloyDBAdminClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod(AlloyDBAdminClient.parse_crypto_key_version_path) + instance_path = staticmethod(AlloyDBAdminClient.instance_path) + parse_instance_path = staticmethod(AlloyDBAdminClient.parse_instance_path) + network_path = staticmethod(AlloyDBAdminClient.network_path) + parse_network_path = staticmethod(AlloyDBAdminClient.parse_network_path) + supported_database_flag_path = staticmethod(AlloyDBAdminClient.supported_database_flag_path) + parse_supported_database_flag_path = staticmethod(AlloyDBAdminClient.parse_supported_database_flag_path) + user_path = staticmethod(AlloyDBAdminClient.user_path) + parse_user_path = staticmethod(AlloyDBAdminClient.parse_user_path) + common_billing_account_path = staticmethod(AlloyDBAdminClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AlloyDBAdminClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AlloyDBAdminClient.common_folder_path) + parse_common_folder_path = staticmethod(AlloyDBAdminClient.parse_common_folder_path) + common_organization_path = staticmethod(AlloyDBAdminClient.common_organization_path) + parse_common_organization_path = staticmethod(AlloyDBAdminClient.parse_common_organization_path) + common_project_path = staticmethod(AlloyDBAdminClient.common_project_path) + parse_common_project_path = staticmethod(AlloyDBAdminClient.parse_common_project_path) + common_location_path = staticmethod(AlloyDBAdminClient.common_location_path) + parse_common_location_path = staticmethod(AlloyDBAdminClient.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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_info.__func__(AlloyDBAdminAsyncClient, 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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_file.__func__(AlloyDBAdminAsyncClient, 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 AlloyDBAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AlloyDBAdminClient).get_transport_class, type(AlloyDBAdminClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AlloyDBAdminTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, ~.AlloyDBAdminTransport]): 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 = AlloyDBAdminClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersAsyncPager: + r"""Lists Clusters 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 alloydb_v1alpha + + async def sample_list_clusters(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.ListClustersRequest, dict]]): + The request object. Message for requesting list of + Clusters + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListClustersAsyncPager: + Message for response to listing + Clusters + 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 = service.ListClustersRequest(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_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_get_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.GetClusterRequest, dict]]): + The request object. Message for getting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1alpha.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetClusterRequest(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_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1alpha + + async def sample_create_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.CreateClusterRequest, dict]]): + The request object. Message for creating a Cluster + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1alpha.types.Cluster`): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_update_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.UpdateClusterRequest, dict]]): + The request object. Message for updating a Cluster + cluster (:class:`google.cloud.alloydb_v1alpha.types.Cluster`): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 = service.UpdateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster, + 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(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_delete_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.DeleteClusterRequest, dict]]): + The request object. Message for deleting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 = service.DeleteClusterRequest(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_cluster, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_promote_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.PromoteClusterRequest, dict]]): + The request object. Message for promoting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.PromoteClusterRequest(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.promote_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, 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"""Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_restore_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1alpha.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.RestoreClusterRequest, dict]]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + request = service.RestoreClusterRequest(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.restore_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.CreateSecondaryClusterRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1alpha.types.Cluster`): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateSecondaryClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_secondary_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesAsyncPager: + r"""Lists Instances 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 alloydb_v1alpha + + async def sample_list_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances + 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 = service.ListInstancesRequest(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_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_get_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.GetInstanceRequest, dict]]): + The request object. Message for getting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1alpha.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetInstanceRequest(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_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1alpha + + async def sample_create_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.CreateInstanceRequest, dict]]): + The request object. Message for creating a Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1alpha.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1alpha + + async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.CreateSecondaryInstanceRequest, dict]]): + The request object. Message for creating a Secondary + Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1alpha.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateSecondaryInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_secondary_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, 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"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1alpha.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.BatchCreateInstancesRequest, dict]]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1alpha.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_instances, + 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_update_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.UpdateInstanceRequest, dict]]): + The request object. Message for updating a Instance + instance (:class:`google.cloud.alloydb_v1alpha.types.Instance`): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 = service.UpdateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance, + 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(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_delete_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.DeleteInstanceRequest, dict]]): + The request object. Message for deleting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 = service.DeleteInstanceRequest(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_instance, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_failover_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.FailoverInstanceRequest, dict]]): + The request object. Message for triggering failover on an + Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.FailoverInstanceRequest(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.failover_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_inject_fault(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.InjectFaultRequest, dict]]): + The request object. Message for triggering fault + injection on an instance + fault_type (:class:`google.cloud.alloydb_v1alpha.types.InjectFaultRequest.FaultType`): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 = service.InjectFaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_restart_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.RestartInstanceRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.RestartInstanceRequest(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.restart_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1alpha + + async def sample_list_backups(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1alpha.types.ListBackupsRequest, dict]]): + The request object. Message for requesting list of + Backups + parent (:class:`str`): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListBackupsAsyncPager: + Message for response to listing + Backups + 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[service.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]] = (), + ) -> resources.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 alloydb_v1alpha + + async def sample_get_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1alpha.types.GetBackupRequest, dict]]): + The request object. Message for getting a Backup + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1alpha.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1alpha + + async def sample_create_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1alpha.types.CreateBackupRequest, dict]]): + The request object. Message for creating a Backup + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.alloydb_v1alpha.types.Backup`): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. ID of the requesting + object. + + 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.alloydb_v1alpha.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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=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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1alpha + + async def sample_update_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.UpdateBackupRequest, dict]]): + The request object. Message for updating a Backup + backup (:class:`google.cloud.alloydb_v1alpha.types.Backup`): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1alpha.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 = service.UpdateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_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(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1alpha + + async def sample_delete_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1alpha.types.DeleteBackupRequest, dict]]): + The request object. Message for deleting a Backup + name (:class:`str`): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 = service.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=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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsAsyncPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1alpha + + async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest, dict]]): + The request object. Message for listing the information + about the supported Database flags. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager: + Message for response to listing + SupportedDatabaseFlags. + 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 = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSupportedDatabaseFlagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_client_certificate(self, + request: Optional[Union[service.GenerateClientCertificateRequest, 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]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.GenerateClientCertificateRequest, dict]]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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.alloydb_v1alpha.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate 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([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 = service.GenerateClientCertificateRequest(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.generate_client_certificate, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_connection_info(self, + request: Optional[Union[service.GetConnectionInfoRequest, 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]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_get_connection_info(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.GetConnectionInfoRequest, dict]]): + The request object. Request message for + GetConnectionInfo. + parent (:class:`str`): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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.alloydb_v1alpha.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetConnectionInfoRequest(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.get_connection_info, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersAsyncPager: + r"""Lists Users 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 alloydb_v1alpha + + async def sample_list_users(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.ListUsersRequest, dict]]): + The request object. Message for requesting list of Users + parent (:class:`str`): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListUsersAsyncPager: + Message for response to listing Users + + 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 = service.ListUsersRequest(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_users, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_get_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.GetUserRequest, dict]]): + The request object. Message for getting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetUserRequest(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_user, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_create_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.CreateUserRequest, dict]]): + The request object. Message for creating a User + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`google.cloud.alloydb_v1alpha.types.User`): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 = service.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_update_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.UpdateUserRequest, dict]]): + The request object. Message for updating a User + user (:class:`google.cloud.alloydb_v1alpha.types.User`): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 = service.UpdateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user, + 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(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + async def sample_delete_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.cloud.alloydb_v1alpha.types.DeleteUserRequest, dict]]): + The request object. Message for deleting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DeleteUserRequest(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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AlloyDBAdminAsyncClient": + 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__ = ( + "AlloyDBAdminAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py new file mode 100644 index 000000000000..5f2710f5d7a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py @@ -0,0 +1,4477 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.alloydb_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.alloydb_v1alpha.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AlloyDBAdminGrpcTransport +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .transports.rest import AlloyDBAdminRestTransport + + +class AlloyDBAdminClientMeta(type): + """Metaclass for the AlloyDBAdmin 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[AlloyDBAdminTransport]] + _transport_registry["grpc"] = AlloyDBAdminGrpcTransport + _transport_registry["grpc_asyncio"] = AlloyDBAdminGrpcAsyncIOTransport + _transport_registry["rest"] = AlloyDBAdminRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AlloyDBAdminTransport]: + """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 AlloyDBAdminClient(metaclass=AlloyDBAdminClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "alloydb.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: + AlloyDBAdminClient: 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: + AlloyDBAdminClient: 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) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, 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.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def connection_info_path(project: str,location: str,cluster: str,instance: str,) -> str: + """Returns a fully-qualified connection_info string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format(project=project, location=location, cluster=cluster, instance=instance, ) + + @staticmethod + def parse_connection_info_path(path: str) -> Dict[str,str]: + """Parses a connection_info path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?P.+?)/connectionInfo$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str,str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_path(project: str,location: str,cluster: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?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 supported_database_flag_path(project: str,location: str,flag: str,) -> str: + """Returns a fully-qualified supported_database_flag string.""" + return "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + + @staticmethod + def parse_supported_database_flag_path(path: str) -> Dict[str,str]: + """Parses a supported_database_flag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/flags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(project: str,location: str,cluster: str,user: str,) -> str: + """Returns a fully-qualified user string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/users/(?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, AlloyDBAdminTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, AlloyDBAdminTransport]): 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, AlloyDBAdminTransport): + # transport is a AlloyDBAdminTransport 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_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersPager: + r"""Lists Clusters 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 alloydb_v1alpha + + def sample_list_clusters(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.ListClustersRequest, dict]): + The request object. Message for requesting list of + Clusters + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListClustersPager: + Message for response to listing + Clusters + 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 service.ListClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListClustersRequest): + request = service.ListClustersRequest(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_clusters] + + # 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.ListClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_get_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GetClusterRequest, dict]): + The request object. Message for getting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1alpha.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetClusterRequest): + request = service.GetClusterRequest(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_cluster] + + # Certain 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_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1alpha + + def sample_create_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.CreateClusterRequest, dict]): + The request object. Message for creating a Cluster + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateClusterRequest): + request = service.CreateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_update_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.UpdateClusterRequest, dict]): + The request object. Message for updating a Cluster + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 service.UpdateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateClusterRequest): + request = service.UpdateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_delete_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.DeleteClusterRequest, dict]): + The request object. Message for deleting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 service.DeleteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteClusterRequest): + request = service.DeleteClusterRequest(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_cluster] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_promote_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.PromoteClusterRequest, dict]): + The request object. Message for promoting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.PromoteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.PromoteClusterRequest): + request = service.PromoteClusterRequest(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.promote_cluster] + + # Certain 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, dict]] = 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 Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_restore_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1alpha.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.RestoreClusterRequest, dict]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.RestoreClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestoreClusterRequest): + request = service.RestoreClusterRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.CreateSecondaryClusterRequest, dict]): + The request object. + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1alpha.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateSecondaryClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryClusterRequest): + request = service.CreateSecondaryClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesPager: + r"""Lists Instances 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 alloydb_v1alpha + + def sample_list_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListInstancesPager: + Message for response to listing + Instances + 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 service.ListInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListInstancesRequest): + request = service.ListInstancesRequest(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_instances] + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_get_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GetInstanceRequest, dict]): + The request object. Message for getting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1alpha.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetInstanceRequest): + request = service.GetInstanceRequest(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_instance] + + # Certain 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_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1alpha + + def sample_create_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.CreateInstanceRequest, dict]): + The request object. Message for creating a Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateInstanceRequest): + request = service.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1alpha + + def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.CreateSecondaryInstanceRequest, dict]): + The request object. Message for creating a Secondary + Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateSecondaryInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryInstanceRequest): + request = service.CreateSecondaryInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_batch_create_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1alpha.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.BatchCreateInstancesRequest, dict]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1alpha.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.BatchCreateInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.BatchCreateInstancesRequest): + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_instances] + + # 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_update_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.UpdateInstanceRequest, dict]): + The request object. Message for updating a Instance + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 service.UpdateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateInstanceRequest): + request = service.UpdateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_delete_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.DeleteInstanceRequest, dict]): + The request object. Message for deleting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 service.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteInstanceRequest): + request = service.DeleteInstanceRequest(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_instance] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_failover_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.FailoverInstanceRequest, dict]): + The request object. Message for triggering failover on an + Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.FailoverInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.FailoverInstanceRequest): + request = service.FailoverInstanceRequest(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.failover_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_inject_fault(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.InjectFaultRequest, dict]): + The request object. Message for triggering fault + injection on an instance + fault_type (google.cloud.alloydb_v1alpha.types.InjectFaultRequest.FaultType): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 service.InjectFaultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.InjectFaultRequest): + request = service.InjectFaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_restart_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.RestartInstanceRequest, dict]): + The request object. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1alpha.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.RestartInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestartInstanceRequest): + request = service.RestartInstanceRequest(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.restart_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1alpha + + def sample_list_backups(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1alpha.types.ListBackupsRequest, dict]): + The request object. Message for requesting list of + Backups + parent (str): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListBackupsPager: + Message for response to listing + Backups + 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 service.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListBackupsRequest): + request = service.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[service.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]] = (), + ) -> resources.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 alloydb_v1alpha + + def sample_get_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GetBackupRequest, dict]): + The request object. Message for getting a Backup + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1alpha.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetBackupRequest): + request = service.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[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1alpha + + def sample_create_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1alpha.types.CreateBackupRequest, dict]): + The request object. Message for creating a Backup + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.alloydb_v1alpha.types.Backup): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. ID of the requesting + object. + + 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.alloydb_v1alpha.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateBackupRequest): + request = service.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1alpha + + def sample_update_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.UpdateBackupRequest, dict]): + The request object. Message for updating a Backup + backup (google.cloud.alloydb_v1alpha.types.Backup): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1alpha.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 service.UpdateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateBackupRequest): + request = service.UpdateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1alpha + + def sample_delete_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1alpha.types.DeleteBackupRequest, dict]): + The request object. Message for deleting a Backup + name (str): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 service.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteBackupRequest): + request = service.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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1alpha + + def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest, dict]): + The request object. Message for listing the information + about the supported Database flags. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager: + Message for response to listing + SupportedDatabaseFlags. + 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 service.ListSupportedDatabaseFlagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSupportedDatabaseFlagsRequest): + request = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags] + + # 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.ListSupportedDatabaseFlagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_client_certificate(self, + request: Optional[Union[service.GenerateClientCertificateRequest, 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]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GenerateClientCertificateRequest, dict]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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.alloydb_v1alpha.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate 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([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 service.GenerateClientCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateClientCertificateRequest): + request = service.GenerateClientCertificateRequest(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.generate_client_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_connection_info(self, + request: Optional[Union[service.GetConnectionInfoRequest, 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]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_get_connection_info(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GetConnectionInfoRequest, dict]): + The request object. Request message for + GetConnectionInfo. + parent (str): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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.alloydb_v1alpha.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetConnectionInfoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetConnectionInfoRequest): + request = service.GetConnectionInfoRequest(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.get_connection_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 = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersPager: + r"""Lists Users 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 alloydb_v1alpha + + def sample_list_users(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.ListUsersRequest, dict]): + The request object. Message for requesting list of Users + parent (str): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListUsersPager: + Message for response to listing Users + + 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 service.ListUsersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListUsersRequest): + request = service.ListUsersRequest(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_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_get_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.GetUserRequest, dict]): + The request object. Message for getting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetUserRequest): + request = service.GetUserRequest(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_user] + + # Certain 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_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_create_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.CreateUserRequest, dict]): + The request object. Message for creating a User + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (google.cloud.alloydb_v1alpha.types.User): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 service.CreateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateUserRequest): + request = service.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_update_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.UpdateUserRequest, dict]): + The request object. Message for updating a User + user (google.cloud.alloydb_v1alpha.types.User): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1alpha.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 service.UpdateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateUserRequest): + request = service.UpdateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1alpha + + def sample_delete_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.cloud.alloydb_v1alpha.types.DeleteUserRequest, dict]): + The request object. Message for deleting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteUserRequest): + request = service.DeleteUserRequest(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_user] + + # Certain 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 __enter__(self) -> "AlloyDBAdminClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AlloyDBAdminClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/pagers.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/pagers.py new file mode 100644 index 000000000000..b5dcccefc2b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/pagers.py @@ -0,0 +1,624 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service + + +class ListClustersPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListClustersResponse` + 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[..., service.ListClustersResponse], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1alpha.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListClustersResponse]: + 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[resources.Cluster]: + for page in self.pages: + yield from page.clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClustersAsyncPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListClustersResponse` + 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[service.ListClustersResponse]], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1alpha.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListClustersResponse]: + 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[resources.Cluster]: + async def async_generator(): + async for page in self.pages: + for response in page.clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListInstancesResponse` + 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[..., service.ListInstancesResponse], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1alpha.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListInstancesResponse]: + 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[resources.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListInstancesResponse` + 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[service.ListInstancesResponse]], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1alpha.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListInstancesResponse]: + 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[resources.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + 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.alloydb_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.alloydb_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[..., service.ListBackupsResponse], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1alpha.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.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[resources.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.alloydb_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.alloydb_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[service.ListBackupsResponse]], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1alpha.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.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[service.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[resources.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) + + +class ListSupportedDatabaseFlagsPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse` + 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[..., service.ListSupportedDatabaseFlagsResponse], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + for page in self.pages: + yield from page.supported_database_flags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSupportedDatabaseFlagsAsyncPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse` + 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[service.ListSupportedDatabaseFlagsResponse]], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + async def async_generator(): + async for page in self.pages: + for response in page.supported_database_flags: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListUsersResponse` + 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[..., service.ListUsersResponse], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1alpha.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListUsersResponse]: + 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[resources.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1alpha.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1alpha.types.ListUsersResponse` + 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[service.ListUsersResponse]], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1alpha.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1alpha.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListUsersResponse]: + 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[resources.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/__init__.py new file mode 100644 index 000000000000..9d544d8e4648 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AlloyDBAdminTransport +from .grpc import AlloyDBAdminGrpcTransport +from .grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .rest import AlloyDBAdminRestTransport +from .rest import AlloyDBAdminRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AlloyDBAdminTransport]] +_transport_registry['grpc'] = AlloyDBAdminGrpcTransport +_transport_registry['grpc_asyncio'] = AlloyDBAdminGrpcAsyncIOTransport +_transport_registry['rest'] = AlloyDBAdminRestTransport + +__all__ = ( + 'AlloyDBAdminTransport', + 'AlloyDBAdminGrpcTransport', + 'AlloyDBAdminGrpcAsyncIOTransport', + 'AlloyDBAdminRestTransport', + 'AlloyDBAdminRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/base.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/base.py new file mode 100644 index 000000000000..aa5d4b07c017 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/base.py @@ -0,0 +1,698 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.alloydb_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.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AlloyDBAdminTransport(abc.ABC): + """Abstract transport class for AlloyDBAdmin.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'alloydb.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_clusters: gapic_v1.method.wrap_method( + self.list_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method.wrap_method( + self.get_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.promote_cluster: gapic_v1.method.wrap_method( + self.promote_cluster, + default_timeout=None, + client_info=client_info, + ), + self.restore_cluster: gapic_v1.method.wrap_method( + self.restore_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_cluster: gapic_v1.method.wrap_method( + self.create_secondary_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_instance: gapic_v1.method.wrap_method( + self.create_secondary_instance, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_instances: gapic_v1.method.wrap_method( + self.batch_create_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_instance: gapic_v1.method.wrap_method( + self.update_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.failover_instance: gapic_v1.method.wrap_method( + self.failover_instance, + default_timeout=None, + client_info=client_info, + ), + self.inject_fault: gapic_v1.method.wrap_method( + self.inject_fault, + default_timeout=None, + client_info=client_info, + ), + self.restart_instance: gapic_v1.method.wrap_method( + self.restart_instance, + default_timeout=None, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=None, + client_info=client_info, + ), + self.update_backup: gapic_v1.method.wrap_method( + self.update_backup, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.list_supported_database_flags: gapic_v1.method.wrap_method( + self.list_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_client_certificate: gapic_v1.method.wrap_method( + self.generate_client_certificate, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_connection_info: gapic_v1.method.wrap_method( + self.get_connection_info, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + 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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Union[ + service.ListClustersResponse, + Awaitable[service.ListClustersResponse] + ]]: + raise NotImplementedError() + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Union[ + resources.Cluster, + Awaitable[resources.Cluster] + ]]: + raise NotImplementedError() + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Union[ + service.ListInstancesResponse, + Awaitable[service.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Union[ + resources.Instance, + Awaitable[resources.Instance] + ]]: + raise NotImplementedError() + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Union[ + service.ListBackupsResponse, + Awaitable[service.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Union[ + resources.Backup, + Awaitable[resources.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [service.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [service.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Union[ + service.ListSupportedDatabaseFlagsResponse, + Awaitable[service.ListSupportedDatabaseFlagsResponse] + ]]: + raise NotImplementedError() + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + Union[ + service.GenerateClientCertificateResponse, + Awaitable[service.GenerateClientCertificateResponse] + ]]: + raise NotImplementedError() + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + Union[ + resources.ConnectionInfo, + Awaitable[resources.ConnectionInfo] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Union[ + service.ListUsersResponse, + Awaitable[service.ListUsersResponse] + ]]: + raise NotImplementedError() + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AlloyDBAdminTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc.py new file mode 100644 index 000000000000..8d7a2e207b72 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc.py @@ -0,0 +1,1210 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import 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.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO + + +class AlloyDBAdminGrpcTransport(AlloyDBAdminTransport): + """gRPC backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + ~.ListClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + ~.Cluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + ~.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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + ~.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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + ~.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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + ~.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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + ~.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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + operations_pb2.Operation]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + ~.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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + ~.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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1alpha.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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.alloydb.v1alpha.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1alpha.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + ~.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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1alpha.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + ~.ListSupportedDatabaseFlagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + ~.GenerateClientCertificateResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_client_certificate' not in self._stubs: + self._stubs['generate_client_certificate'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GenerateClientCertificate', + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs['generate_client_certificate'] + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + resources.ConnectionInfo]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + ~.ConnectionInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connection_info' not in self._stubs: + self._stubs['get_connection_info'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetConnectionInfo', + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs['get_connection_info'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AlloyDBAdminGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc_asyncio.py new file mode 100644 index 000000000000..68eac8bdc4a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/grpc_asyncio.py @@ -0,0 +1,1209 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.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.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .grpc import AlloyDBAdminGrpcTransport + + +class AlloyDBAdminGrpcAsyncIOTransport(AlloyDBAdminTransport): + """gRPC AsyncIO backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Awaitable[service.ListClustersResponse]]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + Awaitable[~.ListClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Awaitable[resources.Cluster]]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + Awaitable[~.Cluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + 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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + 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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Awaitable[service.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Awaitable[resources.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + 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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + 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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + 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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + 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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + 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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Awaitable[service.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1alpha.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Awaitable[resources.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.alloydb.v1alpha.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1alpha.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + 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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1alpha.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Awaitable[service.ListSupportedDatabaseFlagsResponse]]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + Awaitable[~.ListSupportedDatabaseFlagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + Awaitable[service.GenerateClientCertificateResponse]]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + Awaitable[~.GenerateClientCertificateResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_client_certificate' not in self._stubs: + self._stubs['generate_client_certificate'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GenerateClientCertificate', + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs['generate_client_certificate'] + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + Awaitable[resources.ConnectionInfo]]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + Awaitable[~.ConnectionInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connection_info' not in self._stubs: + self._stubs['get_connection_info'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetConnectionInfo', + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs['get_connection_info'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Awaitable[service.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1alpha.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'AlloyDBAdminGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/rest.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/rest.py new file mode 100644 index 000000000000..2202a904a328 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/services/alloy_db_admin/transports/rest.py @@ -0,0 +1,4331 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.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 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.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import AlloyDBAdminTransport, 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 AlloyDBAdminRestInterceptor: + """Interceptor for AlloyDBAdmin. + + 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 AlloyDBAdminRestTransport. + + .. code-block:: python + class MyCustomAlloyDBAdminInterceptor(AlloyDBAdminRestInterceptor): + def pre_batch_create_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_instances(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_failover_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_failover_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_client_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_client_certificate(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_connection_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connection_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_inject_fault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_inject_fault(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_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_supported_database_flags(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_supported_database_flags(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_promote_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_promote_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restart_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restart_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AlloyDBAdminRestTransport(interceptor=MyCustomAlloyDBAdminInterceptor()) + client = AlloyDBAdminClient(transport=transport) + + + """ + def pre_batch_create_instances(self, request: service.BatchCreateInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.BatchCreateInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_batch_create_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_backup(self, request: service.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_cluster(self, request: service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_instance(self, request: service.CreateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_cluster(self, request: service.CreateSecondaryClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_instance(self, request: service.CreateSecondaryInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_user(self, request: service.CreateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for create_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: service.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_cluster(self, request: service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_instance(self, request: service.DeleteInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_user(self, request: service.DeleteUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def pre_failover_instance(self, request: service.FailoverInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.FailoverInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for failover_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for failover_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_generate_client_certificate(self, request: service.GenerateClientCertificateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateClientCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_generate_client_certificate(self, response: service.GenerateClientCertificateResponse) -> service.GenerateClientCertificateResponse: + """Post-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: service.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_get_backup(self, response: resources.Backup) -> resources.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_cluster(self, request: service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: + """Post-rpc interceptor for get_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_connection_info(self, request: service.GetConnectionInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetConnectionInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_connection_info(self, response: resources.ConnectionInfo) -> resources.ConnectionInfo: + """Post-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_instance(self, response: resources.Instance) -> resources.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_user(self, request: service.GetUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for get_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_inject_fault(self, request: service.InjectFaultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.InjectFaultRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for inject_fault + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_inject_fault(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for inject_fault + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: service.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_list_backups(self, response: service.ListBackupsResponse) -> service.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_clusters(self, request: service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_clusters(self, response: service.ListClustersResponse) -> service.ListClustersResponse: + """Post-rpc interceptor for list_clusters + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_instances(self, request: service.ListInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_instances(self, response: service.ListInstancesResponse) -> service.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_supported_database_flags(self, request: service.ListSupportedDatabaseFlagsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListSupportedDatabaseFlagsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_supported_database_flags(self, response: service.ListSupportedDatabaseFlagsResponse) -> service.ListSupportedDatabaseFlagsResponse: + """Post-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_users(self, request: service.ListUsersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListUsersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_users(self, response: service.ListUsersResponse) -> service.ListUsersResponse: + """Post-rpc interceptor for list_users + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_promote_cluster(self, request: service.PromoteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.PromoteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_promote_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restart_instance(self, request: service.RestartInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestartInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restart_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restart_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restart_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restore_cluster(self, request: service.RestoreClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestoreClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restore_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_backup(self, request: service.UpdateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_cluster(self, request: service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_instance(self, request: service.UpdateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_user(self, request: service.UpdateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for update_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AlloyDBAdminRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AlloyDBAdminRestInterceptor + + +class AlloyDBAdminRestTransport(AlloyDBAdminTransport): + """REST backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'alloydb.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[AlloyDBAdminRestInterceptor] = 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 AlloyDBAdminRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + '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 _BatchCreateInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("BatchCreateInstances") + + __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: service.BatchCreateInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch create instances method over HTTP. + + Args: + request (~.service.BatchCreateInstancesRequest): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:batchCreate', + 'body': 'requests', + }, + ] + request, metadata = self._interceptor.pre_batch_create_instances(request, metadata) + pb_request = service.BatchCreateInstancesRequest.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_batch_create_instances(resp) + return resp + + class _CreateBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.CreateBackupRequest): + The request object. Message for creating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = service.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 _CreateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create cluster method over HTTP. + + Args: + request (~.service.CreateClusterRequest): + The request object. Message for creating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_cluster(request, metadata) + pb_request = service.CreateClusterRequest.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_cluster(resp) + return resp + + class _CreateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.service.CreateInstanceRequest): + The request object. Message for creating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_instance(request, metadata) + pb_request = service.CreateInstanceRequest.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_instance(resp) + return resp + + class _CreateSecondaryCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary cluster method over HTTP. + + Args: + request (~.service.CreateSecondaryClusterRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/*}/clusters:createsecondary', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_cluster(request, metadata) + pb_request = service.CreateSecondaryClusterRequest.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_secondary_cluster(resp) + return resp + + class _CreateSecondaryInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary instance method over HTTP. + + Args: + request (~.service.CreateSecondaryInstanceRequest): + The request object. Message for creating a Secondary + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:createsecondary', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_instance(request, metadata) + pb_request = service.CreateSecondaryInstanceRequest.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_secondary_instance(resp) + return resp + + class _CreateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateUser") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the create user method over HTTP. + + Args: + request (~.service.CreateUserRequest): + The request object. Message for creating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/clusters/*}/users', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_create_user(request, metadata) + pb_request = service.CreateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_user(resp) + return resp + + class _DeleteBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.DeleteBackupRequest): + The request object. Message for deleting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = service.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 _DeleteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteCluster") + + __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: service.DeleteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete cluster method over HTTP. + + Args: + request (~.service.DeleteClusterRequest): + The request object. Message for deleting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + pb_request = service.DeleteClusterRequest.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_cluster(resp) + return resp + + class _DeleteInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteInstance") + + __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: service.DeleteInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.service.DeleteInstanceRequest): + The request object. Message for deleting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + pb_request = service.DeleteInstanceRequest.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_instance(resp) + return resp + + class _DeleteUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteUser") + + __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: service.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.service.DeleteUserRequest): + The request object. Message for deleting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user(request, metadata) + pb_request = service.DeleteUserRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FailoverInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("FailoverInstance") + + __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: service.FailoverInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the failover instance method over HTTP. + + Args: + request (~.service.FailoverInstanceRequest): + The request object. Message for triggering failover on an + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:failover', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_failover_instance(request, metadata) + pb_request = service.FailoverInstanceRequest.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_failover_instance(resp) + return resp + + class _GenerateClientCertificate(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GenerateClientCertificate") + + __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: service.GenerateClientCertificateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.GenerateClientCertificateResponse: + r"""Call the generate client + certificate method over HTTP. + + Args: + request (~.service.GenerateClientCertificateRequest): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_client_certificate(request, metadata) + pb_request = service.GenerateClientCertificateRequest.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 = service.GenerateClientCertificateResponse() + pb_resp = service.GenerateClientCertificateResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_client_certificate(resp) + return resp + + class _GetBackup(AlloyDBAdminRestStub): + 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: service.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.service.GetBackupRequest): + The request object. Message for getting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Backup: + Message describing Backup object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = service.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 = resources.Backup() + pb_resp = resources.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetCluster") + + __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: service.GetClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Cluster: + r"""Call the get cluster method over HTTP. + + Args: + request (~.service.GetClusterRequest): + The request object. Message for getting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_cluster(request, metadata) + pb_request = service.GetClusterRequest.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 = resources.Cluster() + pb_resp = resources.Cluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + return resp + + class _GetConnectionInfo(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetConnectionInfo") + + __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: service.GetConnectionInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConnectionInfo: + r"""Call the get connection info method over HTTP. + + Args: + request (~.service.GetConnectionInfoRequest): + The request object. Request message for + GetConnectionInfo. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo', + }, + ] + request, metadata = self._interceptor.pre_get_connection_info(request, metadata) + pb_request = service.GetConnectionInfoRequest.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 = resources.ConnectionInfo() + pb_resp = resources.ConnectionInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connection_info(resp) + return resp + + class _GetInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetInstance") + + __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: service.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.service.GetInstanceRequest): + The request object. Message for getting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = service.GetInstanceRequest.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 = resources.Instance() + pb_resp = resources.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetUser") + + __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: service.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the get user method over HTTP. + + Args: + request (~.service.GetUserRequest): + The request object. Message for getting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user(request, metadata) + pb_request = service.GetUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_user(resp) + return resp + + class _InjectFault(AlloyDBAdminRestStub): + def __hash__(self): + return hash("InjectFault") + + __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: service.InjectFaultRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the inject fault method over HTTP. + + Args: + request (~.service.InjectFaultRequest): + The request object. Message for triggering fault + injection on an instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_inject_fault(request, metadata) + pb_request = service.InjectFaultRequest.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_inject_fault(resp) + return resp + + class _ListBackups(AlloyDBAdminRestStub): + 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: service.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.service.ListBackupsRequest): + The request object. Message for requesting list of + Backups + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListBackupsResponse: + Message for response to listing + Backups + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = service.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 = service.ListBackupsResponse() + pb_resp = service.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListClusters(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListClusters") + + __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: service.ListClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListClustersResponse: + r"""Call the list clusters method over HTTP. + + Args: + request (~.service.ListClustersRequest): + The request object. Message for requesting list of + Clusters + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListClustersResponse: + Message for response to listing + Clusters + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/clusters', + }, + ] + request, metadata = self._interceptor.pre_list_clusters(request, metadata) + pb_request = service.ListClustersRequest.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 = service.ListClustersResponse() + pb_resp = service.ListClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + return resp + + class _ListInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListInstances") + + __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: service.ListInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.service.ListInstancesRequest): + The request object. Message for requesting list of + Instances + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListInstancesResponse: + Message for response to listing + Instances + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/clusters/*}/instances', + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = service.ListInstancesRequest.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 = service.ListInstancesResponse() + pb_resp = service.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListSupportedDatabaseFlags(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListSupportedDatabaseFlags") + + __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: service.ListSupportedDatabaseFlagsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListSupportedDatabaseFlagsResponse: + r"""Call the list supported database + flags method over HTTP. + + Args: + request (~.service.ListSupportedDatabaseFlagsRequest): + The request object. Message for listing the information + about the supported Database flags. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListSupportedDatabaseFlagsResponse: + Message for response to listing + SupportedDatabaseFlags. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/supportedDatabaseFlags', + }, + ] + request, metadata = self._interceptor.pre_list_supported_database_flags(request, metadata) + pb_request = service.ListSupportedDatabaseFlagsRequest.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 = service.ListSupportedDatabaseFlagsResponse() + pb_resp = service.ListSupportedDatabaseFlagsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_supported_database_flags(resp) + return resp + + class _ListUsers(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListUsers") + + __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: service.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.service.ListUsersRequest): + The request object. Message for requesting list of Users + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListUsersResponse: + Message for response to listing Users + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/clusters/*}/users', + }, + ] + request, metadata = self._interceptor.pre_list_users(request, metadata) + pb_request = service.ListUsersRequest.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 = service.ListUsersResponse() + pb_resp = service.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_users(resp) + return resp + + class _PromoteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("PromoteCluster") + + __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: service.PromoteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the promote cluster method over HTTP. + + Args: + request (~.service.PromoteClusterRequest): + The request object. Message for promoting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*}:promote', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_promote_cluster(request, metadata) + pb_request = service.PromoteClusterRequest.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_promote_cluster(resp) + return resp + + class _RestartInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestartInstance") + + __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: service.RestartInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restart instance method over HTTP. + + Args: + request (~.service.RestartInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/{name=projects/*/locations/*/clusters/*/instances/*}:restart', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restart_instance(request, metadata) + pb_request = service.RestartInstanceRequest.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_restart_instance(resp) + return resp + + class _RestoreCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestoreCluster") + + __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: service.RestoreClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore cluster method over HTTP. + + Args: + request (~.service.RestoreClusterRequest): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_cluster(request, metadata) + pb_request = service.RestoreClusterRequest.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_cluster(resp) + return resp + + class _UpdateBackup(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateBackup") + + __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: service.UpdateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update backup method over HTTP. + + Args: + request (~.service.UpdateBackupRequest): + The request object. Message for updating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{backup.name=projects/*/locations/*/backups/*}', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_update_backup(request, metadata) + pb_request = service.UpdateBackupRequest.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_backup(resp) + return resp + + class _UpdateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateCluster") + + __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: service.UpdateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.service.UpdateClusterRequest): + The request object. Message for updating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{cluster.name=projects/*/locations/*/clusters/*}', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + pb_request = service.UpdateClusterRequest.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_cluster(resp) + return resp + + class _UpdateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateInstance") + + __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: service.UpdateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. + + Args: + request (~.service.UpdateInstanceRequest): + The request object. Message for updating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_update_instance(request, metadata) + pb_request = service.UpdateInstanceRequest.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_instance(resp) + return resp + + class _UpdateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateUser") + + __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: service.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the update user method over HTTP. + + Args: + request (~.service.UpdateUserRequest): + The request object. Message for updating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{user.name=projects/*/locations/*/clusters/*/users/*}', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_update_user(request, metadata) + pb_request = service.UpdateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_user(resp) + return resp + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + 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._BatchCreateInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.CreateClusterRequest], + 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._CreateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + 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._CreateSecondaryCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + 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._CreateSecondaryInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + 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._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + 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._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateClientCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + resources.ConnectionInfo]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConnectionInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + 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._InjectFault(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSupportedDatabaseFlags(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + 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._PromoteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + 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._RestartInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + 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._RestoreCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + 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._UpdateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + 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._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUser(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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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 cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(AlloyDBAdminRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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__=( + 'AlloyDBAdminRestTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/__init__.py new file mode 100644 index 000000000000..b4ca84d7f24c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/__init__.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .resources import ( + AutomatedBackupPolicy, + Backup, + BackupSource, + Cluster, + ConnectionInfo, + ContinuousBackupConfig, + ContinuousBackupInfo, + ContinuousBackupSource, + EncryptionConfig, + EncryptionInfo, + Instance, + MigrationSource, + SslConfig, + SupportedDatabaseFlag, + User, + UserPassword, + ClusterView, + DatabaseVersion, + InstanceView, +) +from .service import ( + BatchCreateInstancesMetadata, + BatchCreateInstancesRequest, + BatchCreateInstancesResponse, + BatchCreateInstanceStatus, + CreateBackupRequest, + CreateClusterRequest, + CreateInstanceRequest, + CreateInstanceRequests, + CreateSecondaryClusterRequest, + CreateSecondaryInstanceRequest, + CreateUserRequest, + DeleteBackupRequest, + DeleteClusterRequest, + DeleteInstanceRequest, + DeleteUserRequest, + FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, + GetBackupRequest, + GetClusterRequest, + GetConnectionInfoRequest, + GetInstanceRequest, + GetUserRequest, + InjectFaultRequest, + ListBackupsRequest, + ListBackupsResponse, + ListClustersRequest, + ListClustersResponse, + ListInstancesRequest, + ListInstancesResponse, + ListSupportedDatabaseFlagsRequest, + ListSupportedDatabaseFlagsResponse, + ListUsersRequest, + ListUsersResponse, + OperationMetadata, + PromoteClusterRequest, + RestartInstanceRequest, + RestoreClusterRequest, + UpdateBackupRequest, + UpdateClusterRequest, + UpdateInstanceRequest, + UpdateUserRequest, +) + +__all__ = ( + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ConnectionInfo', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetConnectionInfoRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/resources.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/resources.py new file mode 100644 index 000000000000..9324bde48908 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/resources.py @@ -0,0 +1,1985 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_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 +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1alpha', + manifest={ + 'InstanceView', + 'ClusterView', + 'DatabaseVersion', + 'UserPassword', + 'MigrationSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'SslConfig', + 'AutomatedBackupPolicy', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'BackupSource', + 'ContinuousBackupSource', + 'Cluster', + 'Instance', + 'ConnectionInfo', + 'Backup', + 'SupportedDatabaseFlag', + 'User', + }, +) + + +class InstanceView(proto.Enum): + r"""View on Instance. Pass this enum to rpcs that returns an + Instance message to control which subsets of fields to get. + + Values: + INSTANCE_VIEW_UNSPECIFIED (0): + INSTANCE_VIEW_UNSPECIFIED Not specified, equivalent to + BASIC. + INSTANCE_VIEW_BASIC (1): + BASIC server responses for a primary or read + instance include all the relevant instance + details, excluding the details of each node in + the instance. The default value. + INSTANCE_VIEW_FULL (2): + FULL response is equivalent to BASIC for + primary instance (for now). For read pool + instance, this includes details of each node in + the pool. + """ + INSTANCE_VIEW_UNSPECIFIED = 0 + INSTANCE_VIEW_BASIC = 1 + INSTANCE_VIEW_FULL = 2 + + +class ClusterView(proto.Enum): + r"""View on Cluster. Pass this enum to rpcs that returns a + cluster message to control which subsets of fields to get. + + Values: + CLUSTER_VIEW_UNSPECIFIED (0): + CLUSTER_VIEW_UNSPECIFIED Not specified, equivalent to BASIC. + CLUSTER_VIEW_BASIC (1): + BASIC server responses include all the + relevant cluster details, excluding + Cluster.ContinuousBackupInfo.EarliestRestorableTime + and other view-specific fields. The default + value. + CLUSTER_VIEW_CONTINUOUS_BACKUP (2): + CONTINUOUS_BACKUP response returns all the fields from BASIC + plus the earliest restorable time if continuous backups are + enabled. May increase latency. + """ + CLUSTER_VIEW_UNSPECIFIED = 0 + CLUSTER_VIEW_BASIC = 1 + CLUSTER_VIEW_CONTINUOUS_BACKUP = 2 + + +class DatabaseVersion(proto.Enum): + r"""The supported database engine versions. + + Values: + DATABASE_VERSION_UNSPECIFIED (0): + This is an unknown database version. + POSTGRES_13 (1): + DEPRECATED - The database version is Postgres + 13. + POSTGRES_14 (2): + The database version is Postgres 14. + """ + DATABASE_VERSION_UNSPECIFIED = 0 + POSTGRES_13 = 1 + POSTGRES_14 = 2 + + +class UserPassword(proto.Message): + r"""The username/password for a database user. Used for + specifying initial users at cluster creation time. + + Attributes: + user (str): + The database username. + password (str): + The initial password for the user. + """ + + user: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MigrationSource(proto.Message): + r"""Subset of the source instance configuration that is available + when reading the cluster resource. + + Attributes: + host_port (str): + Output only. The host and port of the + on-premises instance in host:port format + reference_id (str): + Output only. Place holder for the external + source identifier(e.g DMS job name) that created + the cluster. + source_type (google.cloud.alloydb_v1alpha.types.MigrationSource.MigrationSourceType): + Output only. Type of migration source. + """ + class MigrationSourceType(proto.Enum): + r"""Denote the type of migration source that created this + cluster. + + Values: + MIGRATION_SOURCE_TYPE_UNSPECIFIED (0): + Migration source is unknown. + DMS (1): + DMS source means the cluster was created via + DMS migration job. + """ + MIGRATION_SOURCE_TYPE_UNSPECIFIED = 0 + DMS = 1 + + host_port: str = proto.Field( + proto.STRING, + number=1, + ) + reference_id: str = proto.Field( + proto.STRING, + number=2, + ) + source_type: MigrationSourceType = proto.Field( + proto.ENUM, + number=3, + enum=MigrationSourceType, + ) + + +class EncryptionConfig(proto.Message): + r"""EncryptionConfig describes the encryption config of a cluster + or a backup that is encrypted with a CMEK (customer-managed + encryption key). + + Attributes: + kms_key_name (str): + The fully-qualified resource name of the KMS key. Each Cloud + KMS key is regionalized and has the following format: + projects/[PROJECT]/locations/[REGION]/keyRings/[RING]/cryptoKeys/[KEY_NAME] + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptionInfo(proto.Message): + r"""EncryptionInfo describes the encryption information of a + cluster or a backup. + + Attributes: + encryption_type (google.cloud.alloydb_v1alpha.types.EncryptionInfo.Type): + Output only. Type of encryption. + kms_key_versions (MutableSequence[str]): + Output only. Cloud KMS key versions that are + being used to protect the database or the + backup. + """ + class Type(proto.Enum): + r"""Possible encryption types. + + Values: + TYPE_UNSPECIFIED (0): + Encryption type not specified. Defaults to + GOOGLE_DEFAULT_ENCRYPTION. + GOOGLE_DEFAULT_ENCRYPTION (1): + The data is encrypted at rest with a key that + is fully managed by Google. No key version will + be populated. This is the default state. + CUSTOMER_MANAGED_ENCRYPTION (2): + The data is encrypted at rest with a key that + is managed by the customer. KMS key versions + will be populated. + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DEFAULT_ENCRYPTION = 1 + CUSTOMER_MANAGED_ENCRYPTION = 2 + + encryption_type: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class SslConfig(proto.Message): + r"""SSL configuration. + + Attributes: + ssl_mode (google.cloud.alloydb_v1alpha.types.SslConfig.SslMode): + Optional. SSL mode. Specifies client-server + SSL/TLS connection behavior. + ca_source (google.cloud.alloydb_v1alpha.types.SslConfig.CaSource): + Optional. Certificate Authority (CA) source. Only + CA_SOURCE_MANAGED is supported currently, and is the default + value. + """ + class SslMode(proto.Enum): + r"""SSL mode options. + + Values: + SSL_MODE_UNSPECIFIED (0): + SSL mode not specified. Defaults to ENCRYPTED_ONLY. + SSL_MODE_ALLOW (1): + SSL connections are optional. CA verification + not enforced. + SSL_MODE_REQUIRE (2): + SSL connections are required. CA verification + not enforced. Clients may use locally + self-signed certificates (default psql client + behavior). + SSL_MODE_VERIFY_CA (3): + SSL connections are required. CA verification + enforced. Clients must have certificates signed + by a Cluster CA, e.g. via + GenerateClientCertificate. + ALLOW_UNENCRYPTED_AND_ENCRYPTED (4): + SSL connections are optional. CA verification + not enforced. + ENCRYPTED_ONLY (5): + SSL connections are required. CA verification + not enforced. + """ + SSL_MODE_UNSPECIFIED = 0 + SSL_MODE_ALLOW = 1 + SSL_MODE_REQUIRE = 2 + SSL_MODE_VERIFY_CA = 3 + ALLOW_UNENCRYPTED_AND_ENCRYPTED = 4 + ENCRYPTED_ONLY = 5 + + class CaSource(proto.Enum): + r"""Certificate Authority (CA) source for SSL/TLS certificates. + + Values: + CA_SOURCE_UNSPECIFIED (0): + Certificate Authority (CA) source not specified. Defaults to + CA_SOURCE_MANAGED. + CA_SOURCE_MANAGED (1): + Certificate Authority (CA) managed by the + AlloyDB Cluster. + """ + CA_SOURCE_UNSPECIFIED = 0 + CA_SOURCE_MANAGED = 1 + + ssl_mode: SslMode = proto.Field( + proto.ENUM, + number=1, + enum=SslMode, + ) + ca_source: CaSource = proto.Field( + proto.ENUM, + number=2, + enum=CaSource, + ) + + +class AutomatedBackupPolicy(proto.Message): + r"""Message describing the user-specified automated backup + policy. + All fields in the automated backup policy are optional. Defaults + for each field are provided if they are not set. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + weekly_schedule (google.cloud.alloydb_v1alpha.types.AutomatedBackupPolicy.WeeklySchedule): + Weekly schedule for the Backup. + + This field is a member of `oneof`_ ``schedule``. + time_based_retention (google.cloud.alloydb_v1alpha.types.AutomatedBackupPolicy.TimeBasedRetention): + Time-based Backup retention policy. + + This field is a member of `oneof`_ ``retention``. + quantity_based_retention (google.cloud.alloydb_v1alpha.types.AutomatedBackupPolicy.QuantityBasedRetention): + Quantity-based Backup retention policy to + retain recent backups. + + This field is a member of `oneof`_ ``retention``. + enabled (bool): + Whether automated automated backups are + enabled. If not set, defaults to true. + + This field is a member of `oneof`_ ``_enabled``. + backup_window (google.protobuf.duration_pb2.Duration): + The length of the time window during which a + backup can be taken. If a backup does not + succeed within this time window, it will be + canceled and considered failed. + + The backup window must be at least 5 minutes + long. There is no upper bound on the window. If + not set, it defaults to 1 hour. + encryption_config (google.cloud.alloydb_v1alpha.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backups with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + location (str): + The location where the backup will be stored. + Currently, the only supported option is to store + the backup in the same region as the cluster. + + If empty, defaults to the region of the cluster. + labels (MutableMapping[str, str]): + Labels to apply to backups created using this + configuration. + """ + + class WeeklySchedule(proto.Message): + r"""A weekly schedule starts a backup at prescribed start times within a + day, for the specified days of the week. + + The weekly schedule message is flexible and can be used to create + many types of schedules. For example, to have a daily backup that + starts at 22:00, configure the ``start_times`` field to have one + element "22:00" and the ``days_of_week`` field to have all seven + days of the week. + + Attributes: + start_times (MutableSequence[google.type.timeofday_pb2.TimeOfDay]): + The times during the day to start a backup. + The start times are assumed to be in UTC and to + be an exact hour (e.g., 04:00:00). + + If no start times are provided, a single fixed + start time is chosen arbitrarily. + days_of_week (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + The days of the week to perform a backup. + + If this field is left empty, the default of + every day of the week is used. + """ + + start_times: MutableSequence[timeofday_pb2.TimeOfDay] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=timeofday_pb2.TimeOfDay, + ) + days_of_week: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + class TimeBasedRetention(proto.Message): + r"""A time based retention policy specifies that all backups + within a certain time period should be retained. + + Attributes: + retention_period (google.protobuf.duration_pb2.Duration): + The retention period. + """ + + retention_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class QuantityBasedRetention(proto.Message): + r"""A quantity based policy specifies that a certain number of + the most recent successful backups should be retained. + + Attributes: + count (int): + The number of backups to retain. + """ + + count: int = proto.Field( + proto.INT32, + number=1, + ) + + weekly_schedule: WeeklySchedule = proto.Field( + proto.MESSAGE, + number=2, + oneof='schedule', + message=WeeklySchedule, + ) + time_based_retention: TimeBasedRetention = proto.Field( + proto.MESSAGE, + number=4, + oneof='retention', + message=TimeBasedRetention, + ) + quantity_based_retention: QuantityBasedRetention = proto.Field( + proto.MESSAGE, + number=5, + oneof='retention', + message=QuantityBasedRetention, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + backup_window: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='EncryptionConfig', + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class ContinuousBackupConfig(proto.Message): + r"""ContinuousBackupConfig describes the continuous backups + recovery configurations of a cluster. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Whether ContinuousBackup is enabled. + + This field is a member of `oneof`_ ``_enabled``. + recovery_window_days (int): + The number of days that are eligible to + restore from using PITR. To support the entire + recovery window, backups and logs are retained + for one day more than the recovery window. If + not set, defaults to 14 days. + encryption_config (google.cloud.alloydb_v1alpha.types.EncryptionConfig): + The encryption config can be specified to + encrypt the backups with a customer-managed + encryption key (CMEK). When this field is not + specified, the backup will then use default + encryption scheme to protect the user data. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + recovery_window_days: int = proto.Field( + proto.INT32, + number=4, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='EncryptionConfig', + ) + + +class ContinuousBackupInfo(proto.Message): + r"""ContinuousBackupInfo describes the continuous backup + properties of a cluster. + + Attributes: + encryption_info (google.cloud.alloydb_v1alpha.types.EncryptionInfo): + Output only. The encryption information for + the WALs and backups required for + ContinuousBackup. + enabled_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When ContinuousBackup was most + recently enabled. Set to null if + ContinuousBackup is not enabled. + schedule (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + Output only. Days of the week on which a + continuous backup is taken. Output only field. + Ignored if passed into the request. + earliest_restorable_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The earliest restorable time + that can be restored to. Output only field. + """ + + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='EncryptionInfo', + ) + enabled_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + schedule: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=dayofweek_pb2.DayOfWeek, + ) + earliest_restorable_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class BackupSource(proto.Message): + r"""Message describing a BackupSource. + + Attributes: + backup_uid (str): + Output only. The system-generated UID of the + backup which was used to create this resource. + The UID is generated when the backup is created, + and it is retained until the backup is deleted. + backup_name (str): + Required. The name of the backup resource with the format: + + - projects/{project}/locations/{region}/backups/{backup_id} + """ + + backup_uid: str = proto.Field( + proto.STRING, + number=2, + ) + backup_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ContinuousBackupSource(proto.Message): + r"""Message describing a ContinuousBackupSource. + + Attributes: + cluster (str): + Required. The source cluster from which to + restore. This cluster must have continuous + backup enabled for this operation to succeed. + For the required format, see the comment on the + Cluster.name field. + point_in_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The point in time to restore to. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + point_in_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Cluster(proto.Message): + r"""A cluster is a collection of regional AlloyDB resources. It + can include a primary instance and one or more read pool + instances. All cluster resources share a storage layer, which + scales as needed. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1alpha.types.BackupSource): + Output only. Cluster created from backup. + + This field is a member of `oneof`_ ``source``. + migration_source (google.cloud.alloydb_v1alpha.types.MigrationSource): + Output only. Cluster created via DMS + migration. + + This field is a member of `oneof`_ ``source``. + name (str): + Output only. The name of the cluster resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + where the cluster ID segment should satisfy the regex + expression ``[a-z0-9-]+``. For more details see + https://google.aip.dev/122. The prefix of the cluster + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Cluster. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1alpha.types.Cluster.State): + Output only. The current serving state of the + cluster. + cluster_type (google.cloud.alloydb_v1alpha.types.Cluster.ClusterType): + Output only. The type of the cluster. This is an output-only + field and it's populated at the Cluster creation time or the + Cluster promotion time. The cluster type is determined by + which RPC was used to create the cluster (i.e. + ``CreateCluster`` vs. ``CreateSecondaryCluster`` + database_version (google.cloud.alloydb_v1alpha.types.DatabaseVersion): + Optional. The database engine major version. + This is an optional field and it is populated at + the Cluster creation time. If a database version + is not supplied at cluster creation time, then a + default database version will be used. + network_config (google.cloud.alloydb_v1alpha.types.Cluster.NetworkConfig): + + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project_number}/global/networks/{network_id}". + This is required to create a cluster. It can be updated, but + it cannot be removed. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Cluster does not + match the user's intended state, and the service + is actively updating the resource to reconcile + them. This can happen due to user-triggered + updates or system actions like failover or + maintenance. + initial_user (google.cloud.alloydb_v1alpha.types.UserPassword): + Input only. Initial user to setup during cluster creation. + Required. If used in ``RestoreCluster`` this is ignored. + automated_backup_policy (google.cloud.alloydb_v1alpha.types.AutomatedBackupPolicy): + The automated backup policy for this cluster. + + If no policy is provided then the default policy + will be used. If backups are supported for the + cluster, the default policy takes one backup a + day, has a backup window of 1 hour, and retains + backups for 14 days. For more information on the + defaults, consult the documentation for the + message type. + ssl_config (google.cloud.alloydb_v1alpha.types.SslConfig): + SSL configuration for this AlloyDB cluster. + encryption_config (google.cloud.alloydb_v1alpha.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the data disks and other + persistent data resources of a cluster with a + customer-managed encryption key (CMEK). When + this field is not specified, the cluster will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1alpha.types.EncryptionInfo): + Output only. The encryption information for + the cluster. + continuous_backup_config (google.cloud.alloydb_v1alpha.types.ContinuousBackupConfig): + Optional. Continuous backup configuration for + this cluster. + continuous_backup_info (google.cloud.alloydb_v1alpha.types.ContinuousBackupInfo): + Output only. Continuous backup properties for + this cluster. + secondary_config (google.cloud.alloydb_v1alpha.types.Cluster.SecondaryConfig): + Cross Region replication config specific to + SECONDARY cluster. + primary_config (google.cloud.alloydb_v1alpha.types.Cluster.PrimaryConfig): + Output only. Cross Region replication config + specific to PRIMARY cluster. + satisfies_pzs (bool): + Reserved for future use. + """ + class State(proto.Enum): + r"""Cluster State + + Values: + STATE_UNSPECIFIED (0): + The state of the cluster is unknown. + READY (1): + The cluster is active and running. + STOPPED (2): + The cluster is stopped. All instances in the + cluster are stopped. Customers can start a + stopped cluster at any point and all their + instances will come back to life with same names + and IP resources. In this state, customer pays + for storage. + Associated backups could also be present in a + stopped cluster. + EMPTY (3): + The cluster is empty and has no associated + resources. All instances, associated storage and + backups have been deleted. + CREATING (4): + The cluster is being created. + DELETING (5): + The cluster is being deleted. + FAILED (6): + The creation of the cluster failed. + BOOTSTRAPPING (7): + The cluster is bootstrapping with data from + some other source. Direct mutations to the + cluster (e.g. adding read pool) are not allowed. + MAINTENANCE (8): + The cluster is under maintenance. AlloyDB + regularly performs maintenance and upgrades on + customer clusters. Updates on the cluster are + not allowed while the cluster is in this state. + PROMOTING (9): + The cluster is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + EMPTY = 3 + CREATING = 4 + DELETING = 5 + FAILED = 6 + BOOTSTRAPPING = 7 + MAINTENANCE = 8 + PROMOTING = 9 + + class ClusterType(proto.Enum): + r"""Type of Cluster + + Values: + CLUSTER_TYPE_UNSPECIFIED (0): + The type of the cluster is unknown. + PRIMARY (1): + Primary cluster that support read and write + operations. + SECONDARY (2): + Secondary cluster that is replicating from + another region. This only supports read. + """ + CLUSTER_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + SECONDARY = 2 + + class NetworkConfig(proto.Message): + r"""Metadata related to network configuration. + + Attributes: + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project_number}/global/networks/{network_id}". + This is required to create a cluster. It can be updated, but + it cannot be removed. + allocated_ip_range (str): + Optional. The name of the allocated IP range for the private + IP AlloyDB cluster. For example: + "google-managed-services-default". If set, the instance IPs + for this cluster will be created in the allocated range. The + range name must comply with RFC 1035. Specifically, the name + must be 1-63 characters long and match the regular + expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. Field name is + intended to be consistent with CloudSQL. + """ + + network: str = proto.Field( + proto.STRING, + number=1, + ) + allocated_ip_range: str = proto.Field( + proto.STRING, + number=2, + ) + + class SecondaryConfig(proto.Message): + r"""Configuration information for the secondary cluster. This + should be set if and only if the cluster is of type SECONDARY. + + Attributes: + primary_cluster_name (str): + The name of the primary cluster name with the format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + """ + + primary_cluster_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class PrimaryConfig(proto.Message): + r"""Configuration for the primary cluster. It has the list of + clusters that are replicating from this cluster. This should be + set if and only if the cluster is of type PRIMARY. + + Attributes: + secondary_cluster_names (MutableSequence[str]): + Output only. Names of the clusters that are + replicating from this cluster. + """ + + secondary_cluster_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + backup_source: 'BackupSource' = proto.Field( + proto.MESSAGE, + number=15, + oneof='source', + message='BackupSource', + ) + migration_source: 'MigrationSource' = proto.Field( + proto.MESSAGE, + number=16, + oneof='source', + message='MigrationSource', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + cluster_type: ClusterType = proto.Field( + proto.ENUM, + number=24, + enum=ClusterType, + ) + database_version: 'DatabaseVersion' = proto.Field( + proto.ENUM, + number=9, + enum='DatabaseVersion', + ) + network_config: NetworkConfig = proto.Field( + proto.MESSAGE, + number=29, + message=NetworkConfig, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=13, + ) + initial_user: 'UserPassword' = proto.Field( + proto.MESSAGE, + number=14, + message='UserPassword', + ) + automated_backup_policy: 'AutomatedBackupPolicy' = proto.Field( + proto.MESSAGE, + number=17, + message='AutomatedBackupPolicy', + ) + ssl_config: 'SslConfig' = proto.Field( + proto.MESSAGE, + number=18, + message='SslConfig', + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=19, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionInfo', + ) + continuous_backup_config: 'ContinuousBackupConfig' = proto.Field( + proto.MESSAGE, + number=27, + message='ContinuousBackupConfig', + ) + continuous_backup_info: 'ContinuousBackupInfo' = proto.Field( + proto.MESSAGE, + number=28, + message='ContinuousBackupInfo', + ) + secondary_config: SecondaryConfig = proto.Field( + proto.MESSAGE, + number=22, + message=SecondaryConfig, + ) + primary_config: PrimaryConfig = proto.Field( + proto.MESSAGE, + number=23, + message=PrimaryConfig, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=30, + ) + + +class Instance(proto.Message): + r"""An Instance is a computing unit that an end customer can + connect to. It's the main unit of computing resources in + AlloyDB. + + Attributes: + name (str): + Output only. The name of the instance resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id}/instances/{instance_id} + where the cluster and instance ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the instance + resource name is the name of the parent resource: + - projects/{project}/locations/{region}/clusters/{cluster_id} + display_name (str): + User-settable and human-readable display name + for the Instance. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1alpha.types.Instance.State): + Output only. The current serving state of the + instance. + instance_type (google.cloud.alloydb_v1alpha.types.Instance.InstanceType): + Required. The type of the instance. Specified + at creation time. + machine_config (google.cloud.alloydb_v1alpha.types.Instance.MachineConfig): + Configurations for the machines that host the + underlying database engine. + availability_type (google.cloud.alloydb_v1alpha.types.Instance.AvailabilityType): + Availability type of an Instance. If empty, defaults to + REGIONAL for primary instances. For read pools, + availability_type is always UNSPECIFIED. Instances in the + read pools are evenly distributed across available zones + within the region (i.e. read pools with more than one node + will have a node in at least two zones). + gce_zone (str): + The Compute Engine zone that the instance + should serve from, per + https://cloud.google.com/compute/docs/regions-zones + This can ONLY be specified for ZONAL instances. + If present for a REGIONAL instance, an error + will be thrown. If this is absent for a ZONAL + instance, instance is created in a random zone + with available capacity. + database_flags (MutableMapping[str, str]): + Database flags. Set at instance level. + + - They are copied from primary instance on read instance + creation. + - Read instances can set new or override existing flags + that are relevant for reads, e.g. for enabling columnar + cache on a read instance. Flags set on read instance may + or may not be present on primary. + + This is a list of "key": "value" pairs. "key": The name of + the flag. These flags are passed at instance setup time, so + include both server options and system variables for + Postgres. Flags are specified with underscores, not hyphens. + "value": The value of the flag. Booleans are set to **on** + for true and **off** for false. This field must be omitted + if the flag doesn't take a value. + writable_node (google.cloud.alloydb_v1alpha.types.Instance.Node): + Output only. This is set for the read-write + VM of the PRIMARY instance only. + nodes (MutableSequence[google.cloud.alloydb_v1alpha.types.Instance.Node]): + Output only. List of available read-only VMs + in this instance, including the standby for a + PRIMARY instance. + query_insights_config (google.cloud.alloydb_v1alpha.types.Instance.QueryInsightsInstanceConfig): + Configuration for query insights. + read_pool_config (google.cloud.alloydb_v1alpha.types.Instance.ReadPoolConfig): + Read pool specific config. + ip_address (str): + Output only. The IP address for the Instance. + This is the connection endpoint for an end-user + application. + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Instance does + not match the user's intended state, and the + service is actively updating the resource to + reconcile them. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + update_policy (google.cloud.alloydb_v1alpha.types.Instance.UpdatePolicy): + Update policy that will be applied during + instance update. This field is not persisted + when you update the instance. To use a + non-default update policy, you must + specify explicitly specify the value in each + update request. + satisfies_pzs (bool): + Reserved for future use. + """ + class State(proto.Enum): + r"""Instance State + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + READY (1): + The instance is active and running. + STOPPED (2): + The instance is stopped. Instance name and IP + resources are preserved. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + MAINTENANCE (5): + The instance is down for maintenance. + FAILED (6): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance. Note: Instances in this state would + tried to be auto-repaired. And Customers should + be able to restart, update or delete these + instances. + BOOTSTRAPPING (8): + Index 7 is used in the producer apis for ROLLED_BACK state. + Keeping that index unused in case that state also needs to + exposed via consumer apis in future. The instance has been + configured to sync data from some other source. + PROMOTING (9): + The instance is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + CREATING = 3 + DELETING = 4 + MAINTENANCE = 5 + FAILED = 6 + BOOTSTRAPPING = 8 + PROMOTING = 9 + + class InstanceType(proto.Enum): + r"""Type of an Instance + + Values: + INSTANCE_TYPE_UNSPECIFIED (0): + The type of the instance is unknown. + PRIMARY (1): + PRIMARY instances support read and write + operations. + READ_POOL (2): + READ POOL instances support read operations only. Each read + pool instance consists of one or more homogeneous nodes. + + - Read pool of size 1 can only have zonal availability. + - Read pools with node count of 2 or more can have regional + availability (nodes are present in 2 or more zones in a + region). + SECONDARY (3): + SECONDARY instances support read operations + only. SECONDARY instance is a cross-region read + replica + """ + INSTANCE_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + READ_POOL = 2 + SECONDARY = 3 + + class AvailabilityType(proto.Enum): + r"""The Availability type of an instance. Potential values: + + - ZONAL: The instance serves data from only one zone. Outages in + that zone affect instance availability. + - REGIONAL: The instance can serve data from more than one zone + in a region (it is highly available). + + Values: + AVAILABILITY_TYPE_UNSPECIFIED (0): + This is an unknown Availability type. + ZONAL (1): + Zonal available instance. + REGIONAL (2): + Regional (or Highly) available instance. + """ + AVAILABILITY_TYPE_UNSPECIFIED = 0 + ZONAL = 1 + REGIONAL = 2 + + class MachineConfig(proto.Message): + r"""MachineConfig describes the configuration of a machine. + + Attributes: + cpu_count (int): + The number of CPU's in the VM instance. + """ + + cpu_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class Node(proto.Message): + r"""Details of a single node in the instance. + Nodes in an AlloyDB instance are ephemereal, they can change + during update, failover, autohealing and resize operations. + + Attributes: + zone_id (str): + The Compute Engine zone of the VM e.g. + "us-central1-b". + id (str): + The identifier of the VM e.g. + "test-read-0601-407e52be-ms3l". + ip (str): + The private IP address of the VM e.g. + "10.57.0.34". + state (str): + Determined by state of the compute VM and + postgres-service health. Compute VM state can + have values listed in + https://cloud.google.com/compute/docs/instances/instance-life-cycle + and postgres-service health can have values: + HEALTHY and UNHEALTHY. + """ + + zone_id: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + ip: str = proto.Field( + proto.STRING, + number=3, + ) + state: str = proto.Field( + proto.STRING, + number=4, + ) + + class QueryInsightsInstanceConfig(proto.Message): + r"""QueryInsights Instance specific configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + record_application_tags (bool): + Record application tags for an instance. + This flag is turned "on" by default. + + This field is a member of `oneof`_ ``_record_application_tags``. + record_client_address (bool): + Record client address for an instance. Client + address is PII information. This flag is turned + "on" by default. + + This field is a member of `oneof`_ ``_record_client_address``. + query_string_length (int): + Query string length. The default value is + 1024. Any integer between 256 and 4500 is + considered valid. + query_plans_per_minute (int): + Number of query execution plans captured by + Insights per minute for all queries combined. + The default value is 5. Any integer between 0 + and 20 is considered valid. + + This field is a member of `oneof`_ ``_query_plans_per_minute``. + """ + + record_application_tags: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + record_client_address: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + query_string_length: int = proto.Field( + proto.UINT32, + number=4, + ) + query_plans_per_minute: int = proto.Field( + proto.UINT32, + number=5, + optional=True, + ) + + class ReadPoolConfig(proto.Message): + r"""Configuration for a read pool instance. + + Attributes: + node_count (int): + Read capacity, i.e. number of nodes in a read + pool instance. + """ + + node_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class UpdatePolicy(proto.Message): + r"""Policy to be used while updating the instance. + + Attributes: + mode (google.cloud.alloydb_v1alpha.types.Instance.UpdatePolicy.Mode): + Mode for updating the instance. + """ + class Mode(proto.Enum): + r"""Specifies the available modes of update. + + Values: + MODE_UNSPECIFIED (0): + Mode is unknown. + DEFAULT (1): + Least disruptive way to apply the update. + FORCE_APPLY (2): + Performs a forced update when applicable. + This will be fast but may incur a downtime. + """ + MODE_UNSPECIFIED = 0 + DEFAULT = 1 + FORCE_APPLY = 2 + + mode: 'Instance.UpdatePolicy.Mode' = proto.Field( + proto.ENUM, + number=1, + enum='Instance.UpdatePolicy.Mode', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + instance_type: InstanceType = proto.Field( + proto.ENUM, + number=9, + enum=InstanceType, + ) + machine_config: MachineConfig = proto.Field( + proto.MESSAGE, + number=10, + message=MachineConfig, + ) + availability_type: AvailabilityType = proto.Field( + proto.ENUM, + number=11, + enum=AvailabilityType, + ) + gce_zone: str = proto.Field( + proto.STRING, + number=12, + ) + database_flags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + writable_node: Node = proto.Field( + proto.MESSAGE, + number=19, + message=Node, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=Node, + ) + query_insights_config: QueryInsightsInstanceConfig = proto.Field( + proto.MESSAGE, + number=21, + message=QueryInsightsInstanceConfig, + ) + read_pool_config: ReadPoolConfig = proto.Field( + proto.MESSAGE, + number=14, + message=ReadPoolConfig, + ) + ip_address: str = proto.Field( + proto.STRING, + number=15, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=16, + ) + etag: str = proto.Field( + proto.STRING, + number=17, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + update_policy: UpdatePolicy = proto.Field( + proto.MESSAGE, + number=22, + message=UpdatePolicy, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=24, + ) + + +class ConnectionInfo(proto.Message): + r"""ConnectionInfo singleton resource. + https://google.aip.dev/156 + + Attributes: + name (str): + The name of the ConnectionInfo singleton resource, e.g.: + projects/{project}/locations/{location}/clusters/\ */instances/*/connectionInfo + This field currently has no semantic meaning. + ip_address (str): + Output only. The IP address for the Instance. + This is the connection endpoint for an end-user + application. + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + instance_uid (str): + Output only. The unique ID of the Instance. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Backup(proto.Message): + r"""Message describing Backup object + + Attributes: + name (str): + Output only. The name of the backup resource with the + format: + + - projects/{project}/locations/{region}/backups/{backup_id} + where the cluster and backup ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the backup + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Backup. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1alpha.types.Backup.State): + Output only. The current state of the backup. + type_ (google.cloud.alloydb_v1alpha.types.Backup.Type): + The backup type, which suggests the trigger + for the backup. + description (str): + User-provided description of the backup. + cluster_uid (str): + Output only. The system-generated UID of the + cluster which was used to create this resource. + cluster_name (str): + Required. The full resource name of the backup source + cluster (e.g., + projects/{project}/locations/{region}/clusters/{cluster_id}). + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation), if + true, indicates that the service is actively + updating the resource. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + encryption_config (google.cloud.alloydb_v1alpha.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backup with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1alpha.types.EncryptionInfo): + Output only. The encryption information for + the backup. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + size_bytes (int): + Output only. The size of the backup in bytes. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which after the backup is eligible + to be garbage collected. It is the duration specified by the + backup's retention policy, added to the backup's + create_time. + expiry_quantity (google.cloud.alloydb_v1alpha.types.Backup.QuantityBasedExpiry): + Output only. The QuantityBasedExpiry of the + backup, specified by the backup's retention + policy. Once the expiry quantity is over + retention, the backup is eligible to be garbage + collected. + satisfies_pzs (bool): + Reserved for future use. + """ + class State(proto.Enum): + r"""Backup State + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + READY (1): + The backup is ready. + CREATING (2): + The backup is creating. + FAILED (3): + The backup failed. + DELETING (4): + The backup is being deleted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + CREATING = 2 + FAILED = 3 + DELETING = 4 + + class Type(proto.Enum): + r"""Backup Type + + Values: + TYPE_UNSPECIFIED (0): + Backup Type is unknown. + ON_DEMAND (1): + ON_DEMAND backups that were triggered by the customer (e.g., + not AUTOMATED). + AUTOMATED (2): + AUTOMATED backups triggered by the automated + backups scheduler pursuant to an automated + backup policy. + CONTINUOUS (3): + CONTINUOUS backups triggered by the automated + backups scheduler due to a continuous backup + policy. + """ + TYPE_UNSPECIFIED = 0 + ON_DEMAND = 1 + AUTOMATED = 2 + CONTINUOUS = 3 + + class QuantityBasedExpiry(proto.Message): + r"""A backup's position in a quantity-based retention queue, of backups + with the same source cluster and type, with length, retention, + specified by the backup's retention policy. Once the position is + greater than the retention, the backup is eligible to be garbage + collected. + + Example: 5 backups from the same source cluster and type with a + quantity-based retention of 3 and denoted by backup_id (position, + retention). + + Safe: backup_5 (1, 3), backup_4, (2, 3), backup_3 (3, 3). Awaiting + garbage collection: backup_2 (4, 3), backup_1 (5, 3) + + Attributes: + retention_count (int): + Output only. The backup's position among its + backups with the same source cluster and type, + by descending chronological order create + time(i.e. newest first). + total_retention_count (int): + Output only. The length of the quantity-based + queue, specified by the backup's retention + policy. + """ + + retention_count: int = proto.Field( + proto.INT32, + number=1, + ) + total_retention_count: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + type_: Type = proto.Field( + proto.ENUM, + number=8, + enum=Type, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + cluster_uid: str = proto.Field( + proto.STRING, + number=18, + ) + cluster_name: str = proto.Field( + proto.STRING, + number=10, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=11, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='EncryptionInfo', + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=16, + ) + size_bytes: int = proto.Field( + proto.INT64, + number=17, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + expiry_quantity: QuantityBasedExpiry = proto.Field( + proto.MESSAGE, + number=20, + message=QuantityBasedExpiry, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=21, + ) + + +class SupportedDatabaseFlag(proto.Message): + r"""SupportedDatabaseFlag gives general information about a database + flag, like type and allowed values. This is a static value that is + defined on the server side, and it cannot be modified by callers. To + set the Database flags on a particular Instance, a caller should + modify the Instance.database_flags field. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_restrictions (google.cloud.alloydb_v1alpha.types.SupportedDatabaseFlag.StringRestrictions): + Restriction on STRING type value. + + This field is a member of `oneof`_ ``restrictions``. + integer_restrictions (google.cloud.alloydb_v1alpha.types.SupportedDatabaseFlag.IntegerRestrictions): + Restriction on INTEGER type value. + + This field is a member of `oneof`_ ``restrictions``. + name (str): + The name of the flag resource, following Google Cloud + conventions, e.g.: + + - projects/{project}/locations/{location}/flags/{flag} This + field currently has no semantic meaning. + flag_name (str): + The name of the database flag, e.g. "max_allowed_packets". + The is a possibly key for the Instance.database_flags map + field. + value_type (google.cloud.alloydb_v1alpha.types.SupportedDatabaseFlag.ValueType): + + accepts_multiple_values (bool): + Whether the database flag accepts multiple + values. If true, a comma-separated list of + stringified values may be specified. + supported_db_versions (MutableSequence[google.cloud.alloydb_v1alpha.types.DatabaseVersion]): + Major database engine versions for which this + flag is supported. + requires_db_restart (bool): + Whether setting or updating this flag on an + Instance requires a database restart. If a flag + that requires database restart is set, the + backend will automatically restart the database + (making sure to satisfy any availability SLO's). + """ + class ValueType(proto.Enum): + r"""ValueType describes the semantic type of the value that the flag + accepts. Regardless of the ValueType, the Instance.database_flags + field accepts the stringified version of the value, i.e. "20" or + "3.14". + + Values: + VALUE_TYPE_UNSPECIFIED (0): + This is an unknown flag type. + STRING (1): + String type flag. + INTEGER (2): + Integer type flag. + FLOAT (3): + Float type flag. + NONE (4): + Denotes that the flag does not accept any + values. + """ + VALUE_TYPE_UNSPECIFIED = 0 + STRING = 1 + INTEGER = 2 + FLOAT = 3 + NONE = 4 + + class StringRestrictions(proto.Message): + r"""Restrictions on STRING type values + + Attributes: + allowed_values (MutableSequence[str]): + The list of allowed values, if bounded. This + field will be empty if there is a unbounded + number of allowed values. + """ + + allowed_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class IntegerRestrictions(proto.Message): + r"""Restrictions on INTEGER type values. + + Attributes: + min_value (google.protobuf.wrappers_pb2.Int64Value): + The minimum value that can be specified, if + applicable. + max_value (google.protobuf.wrappers_pb2.Int64Value): + The maximum value that can be specified, if + applicable. + """ + + min_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int64Value, + ) + max_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + + string_restrictions: StringRestrictions = proto.Field( + proto.MESSAGE, + number=7, + oneof='restrictions', + message=StringRestrictions, + ) + integer_restrictions: IntegerRestrictions = proto.Field( + proto.MESSAGE, + number=8, + oneof='restrictions', + message=IntegerRestrictions, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + flag_name: str = proto.Field( + proto.STRING, + number=2, + ) + value_type: ValueType = proto.Field( + proto.ENUM, + number=3, + enum=ValueType, + ) + accepts_multiple_values: bool = proto.Field( + proto.BOOL, + number=4, + ) + supported_db_versions: MutableSequence['DatabaseVersion'] = proto.RepeatedField( + proto.ENUM, + number=5, + enum='DatabaseVersion', + ) + requires_db_restart: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class User(proto.Message): + r"""Message describing User object. + + Attributes: + name (str): + Output only. Name of the resource in the form + of + projects/{project}/locations/{location}/cluster/{cluster}/users/{user}. + password (str): + Input only. Password for the user. + database_roles (MutableSequence[str]): + Optional. List of database roles this user + has. The database role strings are subject to + the PostgreSQL naming conventions. + user_type (google.cloud.alloydb_v1alpha.types.User.UserType): + Optional. Type of this user. + """ + class UserType(proto.Enum): + r"""Enum that details the user type. + + Values: + USER_TYPE_UNSPECIFIED (0): + Unspecified user type. + ALLOYDB_BUILT_IN (1): + The default user type that authenticates via + password-based authentication. + ALLOYDB_IAM_USER (2): + Database user that can authenticate via + IAM-Based authentication. + """ + USER_TYPE_UNSPECIFIED = 0 + ALLOYDB_BUILT_IN = 1 + ALLOYDB_IAM_USER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + database_roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + user_type: UserType = proto.Field( + proto.ENUM, + number=5, + enum=UserType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/service.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/service.py new file mode 100644 index 000000000000..9dd34f841b89 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/google/cloud/alloydb_v1alpha/types/service.py @@ -0,0 +1,2132 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.alloydb_v1alpha.types import resources +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1alpha', + manifest={ + 'ListClustersRequest', + 'ListClustersResponse', + 'GetClusterRequest', + 'CreateSecondaryClusterRequest', + 'CreateClusterRequest', + 'UpdateClusterRequest', + 'DeleteClusterRequest', + 'PromoteClusterRequest', + 'RestoreClusterRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'CreateInstanceRequest', + 'CreateSecondaryInstanceRequest', + 'CreateInstanceRequests', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstanceStatus', + 'UpdateInstanceRequest', + 'DeleteInstanceRequest', + 'FailoverInstanceRequest', + 'InjectFaultRequest', + 'RestartInstanceRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'UpdateBackupRequest', + 'DeleteBackupRequest', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetConnectionInfoRequest', + 'OperationMetadata', + 'ListUsersRequest', + 'ListUsersResponse', + 'GetUserRequest', + 'CreateUserRequest', + 'UpdateUserRequest', + 'DeleteUserRequest', + }, +) + + +class ListClustersRequest(proto.Message): + r"""Message for requesting list of Clusters + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Cluster.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with the following format: + + - projects/{project}/locations/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListClustersResponse(proto.Message): + r"""Message for response to listing Clusters + + Attributes: + clusters (MutableSequence[google.cloud.alloydb_v1alpha.types.Cluster]): + The list of Cluster + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + clusters: MutableSequence[resources.Cluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Cluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetClusterRequest(proto.Message): + r"""Message for getting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + view (google.cloud.alloydb_v1alpha.types.ClusterView): + Optional. The view of the cluster to return. + Returns all default fields if not set. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.ClusterView = proto.Field( + proto.ENUM, + number=2, + enum=resources.ClusterView, + ) + + +class CreateSecondaryClusterRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object (the + secondary cluster). + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. Configuration of the requesting + object (the secondary cluster). + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class CreateClusterRequest(proto.Message): + r"""Message for creating a Cluster + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateClusterRequest(proto.Message): + r"""Message for updating a Cluster + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if cluster is + not found. In that case, a new cluster is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteClusterRequest(proto.Message): + r"""Message for deleting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + force (bool): + Optional. Whether to cascade delete child + instances for given cluster. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PromoteClusterRequest(proto.Message): + r"""Message for promoting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestoreClusterRequest(proto.Message): + r"""Message for restoring a Cluster from a backup or another + cluster at a given point in time. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1alpha.types.BackupSource): + Backup source. + + This field is a member of `oneof`_ ``source``. + continuous_backup_source (google.cloud.alloydb_v1alpha.types.ContinuousBackupSource): + ContinuousBackup source. Continuous backup + needs to be enabled in the source cluster for + this operation to succeed. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1alpha.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + import request. + """ + + backup_source: resources.BackupSource = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=resources.BackupSource, + ) + continuous_backup_source: resources.ContinuousBackupSource = proto.Field( + proto.MESSAGE, + number=8, + oneof='source', + message=resources.ContinuousBackupSource, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Instance.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with one of the following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1alpha.types.Instance]): + The list of Instance + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Message for getting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + view (google.cloud.alloydb_v1alpha.types.InstanceView): + The view of the instance to return. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.InstanceView = proto.Field( + proto.ENUM, + number=2, + enum=resources.InstanceView, + ) + + +class CreateInstanceRequest(proto.Message): + r"""Message for creating a Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateSecondaryInstanceRequest(proto.Message): + r"""Message for creating a Secondary Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateInstanceRequests(proto.Message): + r"""See usage below for notes. + + Attributes: + create_instance_requests (MutableSequence[google.cloud.alloydb_v1alpha.types.CreateInstanceRequest]): + Required. Primary and read replica instances + to be created. This list should not be empty. + """ + + create_instance_requests: MutableSequence['CreateInstanceRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CreateInstanceRequest', + ) + + +class BatchCreateInstancesRequest(proto.Message): + r"""Message for creating a batch of instances under the specified + cluster. + + Attributes: + parent (str): + Required. The name of the parent resource. + requests (google.cloud.alloydb_v1alpha.types.CreateInstanceRequests): + Required. Resources being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: 'CreateInstanceRequests' = proto.Field( + proto.MESSAGE, + number=2, + message='CreateInstanceRequests', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchCreateInstancesResponse(proto.Message): + r"""Message for creating batches of instances in a cluster. + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1alpha.types.Instance]): + Created instances. + """ + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + + +class BatchCreateInstancesMetadata(proto.Message): + r"""Message for metadata that is specific to BatchCreateInstances API. + NEXT_ID: 3 + + Attributes: + instance_targets (MutableSequence[str]): + The instances being created in the API call. + Each string in this list is the server defined + resource path for target instances in the + request and for the format of each string, see + the comment on the Instance.name field. + instance_statuses (MutableMapping[str, google.cloud.alloydb_v1alpha.types.BatchCreateInstanceStatus]): + A map representing state of the instances involved in the + BatchCreateInstances operation during the operation + execution. The instance state will be in STATE_UNSPECIFIED + state if the instance has not yet been picked up for + processing. The key of the map is the name of the instance + resource. For the format, see the comment on the + Instance.name field. + """ + + instance_targets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + instance_statuses: MutableMapping[str, 'BatchCreateInstanceStatus'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='BatchCreateInstanceStatus', + ) + + +class BatchCreateInstanceStatus(proto.Message): + r"""Message for current status of an instance in the + BatchCreateInstances operation. For example, lets say a + BatchCreateInstances workflow has 4 instances, Instance1 through + Instance4. Lets also assume that 2 instances succeeded but the third + failed to create and the 4th was never picked up for creation + because of failure of the previous one. Then, resulting states would + look something like: + + 1. Instance1 = ROLLED_BACK + 2. Instance2 = ROLLED_BACK + 3. Instance3 = FAILED + 4. Instance4 = FAILED + + However, while the operation is running, the instance might be in + other states including PENDING_CREATE, ACTIVE, DELETING and + CREATING. The states / do not get further updated once the operation + is done. + + Attributes: + state (google.cloud.alloydb_v1alpha.types.BatchCreateInstanceStatus.State): + The current state of an instance involved in the batch + create operation. Once the operation is complete, the final + state of the instances in the LRO can be one of: + + 1. ACTIVE, indicating that instances were created + successfully + 2. FAILED, indicating that a particular instance failed + creation + 3. ROLLED_BACK indicating that although the instance was + created successfully, it had to be rolled back and + deleted due to failure in other steps of the workflow. + error_msg (str): + DEPRECATED - Use the error field instead. + Error, if any error occurred and is available, + during instance creation. + error (google.rpc.status_pb2.Status): + The RPC status of the instance creation + operation. This field will be present if an + error happened during the instance creation. + type_ (google.cloud.alloydb_v1alpha.types.Instance.InstanceType): + + """ + class State(proto.Enum): + r"""State contains all valid instance states for the + BatchCreateInstances operation. This is mainly used for status + reporting through the LRO metadata. + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + PENDING_CREATE (1): + Instance is pending creation and has not yet + been picked up for processsing in the backend. + READY (2): + The instance is active and running. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + FAILED (5): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance or a batch of instances. + ROLLED_BACK (6): + The instance was created successfully, but + was rolled back and deleted due to some other + failure during BatchCreateInstances operation. + """ + STATE_UNSPECIFIED = 0 + PENDING_CREATE = 1 + READY = 2 + CREATING = 3 + DELETING = 4 + FAILED = 5 + ROLLED_BACK = 6 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + error_msg: str = proto.Field( + proto.STRING, + number=2, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + type_: resources.Instance.InstanceType = proto.Field( + proto.ENUM, + number=3, + enum=resources.Instance.InstanceType, + ) + + +class UpdateInstanceRequest(proto.Message): + r"""Message for updating a Instance + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + instance (google.cloud.alloydb_v1alpha.types.Instance): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new instance is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Message for deleting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Instance. + If an etag is provided and does not match the + current etag of the Instance, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class FailoverInstanceRequest(proto.Message): + r"""Message for triggering failover on an Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + failover. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class InjectFaultRequest(proto.Message): + r"""Message for triggering fault injection on an instance + + Attributes: + fault_type (google.cloud.alloydb_v1alpha.types.InjectFaultRequest.FaultType): + Required. The type of fault to be injected in + an instance. + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + fault injection. + """ + class FaultType(proto.Enum): + r"""FaultType contains all valid types of faults that can be + injected to an instance. + + Values: + FAULT_TYPE_UNSPECIFIED (0): + The fault type is unknown. + STOP_VM (1): + Stop the VM + """ + FAULT_TYPE_UNSPECIFIED = 0 + STOP_VM = 1 + + fault_type: FaultType = proto.Field( + proto.ENUM, + number=1, + enum=FaultType, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestartInstanceRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + restart. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Message for requesting list of Backups + + Attributes: + parent (str): + Required. Parent value for ListBackupsRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListBackupsResponse(proto.Message): + r"""Message for response to listing Backups + + Attributes: + backups (MutableSequence[google.cloud.alloydb_v1alpha.types.Backup]): + The list of Backup + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence[resources.Backup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.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"""Message for getting a Backup + + Attributes: + name (str): + Required. Name of the resource + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Message for creating a Backup + + Attributes: + parent (str): + Required. Value for parent. + backup_id (str): + Required. ID of the requesting object. + backup (google.cloud.alloydb_v1alpha.types.Backup): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateBackupRequest(proto.Message): + r"""Message for updating a Backup + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + backup (google.cloud.alloydb_v1alpha.types.Backup): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new backup is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Message for deleting a Backup + + Attributes: + name (str): + Required. Name of the resource. For the + required format, see the comment on the + Backup.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + etag (str): + Optional. The current etag of the Backup. + If an etag is provided and does not match the + current etag of the Backup, deletion will be + blocked and an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSupportedDatabaseFlagsRequest(proto.Message): + r"""Message for listing the information about the supported + Database flags. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note that + we do not yet support region-specific flags. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSupportedDatabaseFlagsResponse(proto.Message): + r"""Message for response to listing SupportedDatabaseFlags. + + Attributes: + supported_database_flags (MutableSequence[google.cloud.alloydb_v1alpha.types.SupportedDatabaseFlag]): + The list of SupportedDatabaseFlags. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + supported_database_flags: MutableSequence[resources.SupportedDatabaseFlag] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.SupportedDatabaseFlag, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateClientCertificateRequest(proto.Message): + r"""Message for requests to generate a client certificate signed + by the Cluster CA. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + pem_csr (str): + Optional. A pem-encoded X.509 certificate + signing request (CSR). + cert_duration (google.protobuf.duration_pb2.Duration): + Optional. An optional hint to the endpoint to + generate the client certificate with the + requested duration. The duration can be from 1 + hour to 24 hours. The endpoint may or may not + honor the hint. If the hint is left unspecified + or is not honored, then the endpoint will pick + an appropriate default duration. + public_key (str): + Optional. The public key from the client. + use_metadata_exchange (bool): + Optional. An optional hint to the endpoint to + generate a client ceritificate that can be used + by AlloyDB connectors to exchange additional + metadata with the server after TLS handshake. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + pem_csr: str = proto.Field( + proto.STRING, + number=3, + ) + cert_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + public_key: str = proto.Field( + proto.STRING, + number=5, + ) + use_metadata_exchange: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class GenerateClientCertificateResponse(proto.Message): + r"""Message returned by a GenerateClientCertificate operation. + + Attributes: + pem_certificate (str): + Output only. The pem-encoded, signed X.509 + certificate. + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + ca_cert (str): + Optional. The pem-encoded cluster ca X.509 + certificate. + """ + + pem_certificate: str = proto.Field( + proto.STRING, + number=1, + ) + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + ca_cert: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetConnectionInfoRequest(proto.Message): + r"""Request message for GetConnectionInfo. + + Attributes: + parent (str): + Required. The name of the parent resource. + The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + batch_create_instances_metadata (google.cloud.alloydb_v1alpha.types.BatchCreateInstancesMetadata): + Output only. BatchCreateInstances related + metadata. + + This field is a member of `oneof`_ ``request_specific``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + 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. + """ + + batch_create_instances_metadata: 'BatchCreateInstancesMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='request_specific', + message='BatchCreateInstancesMetadata', + ) + 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 ListUsersRequest(proto.Message): + r"""Message for requesting list of Users + + Attributes: + parent (str): + Required. Parent value for ListUsersRequest + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListUsersResponse(proto.Message): + r"""Message for response to listing Users + + Attributes: + users (MutableSequence[google.cloud.alloydb_v1alpha.types.User]): + The list of User + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence[resources.User] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.User, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetUserRequest(proto.Message): + r"""Message for getting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserRequest(proto.Message): + r"""Message for creating a User + + Attributes: + parent (str): + Required. Value for parent. + user_id (str): + Required. ID of the requesting object. + user (google.cloud.alloydb_v1alpha.types.User): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=3, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateUserRequest(proto.Message): + r"""Message for updating a User + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + user (google.cloud.alloydb_v1alpha.types.User): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. Allow missing fields in the update + mask. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=2, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteUserRequest(proto.Message): + r"""Message for deleting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/mypy.ini b/owl-bot-staging/google-cloud-alloydb/v1alpha/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/noxfile.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/noxfile.py new file mode 100644 index 000000000000..d7063556d783 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/alloydb_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==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_async.py new file mode 100644 index 000000000000..c375b1cb4e51 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1alpha + + +async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1alpha.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_sync.py new file mode 100644 index 000000000000..928c1bc375ef --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1alpha + + +def sample_batch_create_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1alpha.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_async.py new file mode 100644 index 000000000000..cfbf8a2fc57e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +async def sample_create_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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 alloydb_v1alpha_generated_AlloyDBAdmin_CreateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_sync.py new file mode 100644 index 000000000000..cea8f34c7e4c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_backup_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +def sample_create_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_async.py new file mode 100644 index 000000000000..55e08989b41d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1alpha + + +async def sample_create_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_sync.py new file mode 100644 index 000000000000..2a03adb71cd6 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1alpha + + +def sample_create_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_async.py new file mode 100644 index 000000000000..ef9616ae6bdc --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1alpha + + +async def sample_create_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_sync.py new file mode 100644 index 000000000000..d82432b1a0a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1alpha + + +def sample_create_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_async.py new file mode 100644 index 000000000000..0634982b6e3b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1alpha + + +async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_sync.py new file mode 100644 index 000000000000..3d786c1001f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1alpha + + +def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_async.py new file mode 100644 index 000000000000..533ed6e34606 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1alpha + + +async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_sync.py new file mode 100644 index 000000000000..f1c4bd0bb07f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1alpha + + +def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_async.py new file mode 100644 index 000000000000..51e31db21ecb --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1alpha + + +async def sample_create_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_sync.py new file mode 100644 index 000000000000..57ebc102d78e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_create_user_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1alpha + + +def sample_create_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_async.py new file mode 100644 index 000000000000..b0ca2287c5c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +async def sample_delete_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1alpha_generated_AlloyDBAdmin_DeleteBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_sync.py new file mode 100644 index 000000000000..31c67306b60d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +def sample_delete_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1alpha_generated_AlloyDBAdmin_DeleteBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_async.py new file mode 100644 index 000000000000..ccb2700fed36 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1alpha + + +async def sample_delete_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_sync.py new file mode 100644 index 000000000000..bf248019e0b3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1alpha + + +def sample_delete_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_async.py new file mode 100644 index 000000000000..e7ac794cee2e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1alpha + + +async def sample_delete_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_sync.py new file mode 100644 index 000000000000..4dfa3a0ee8a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1alpha + + +def sample_delete_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_async.py new file mode 100644 index 000000000000..526ed0c04df9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1alpha + + +async def sample_delete_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_sync.py new file mode 100644 index 000000000000..f7ebdd6dc263 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_delete_user_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1alpha + + +def sample_delete_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_async.py new file mode 100644 index 000000000000..354c84f3beaa --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1alpha + + +async def sample_failover_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_sync.py new file mode 100644 index 000000000000..251bb94aa580 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_failover_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1alpha + + +def sample_failover_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_async.py new file mode 100644 index 000000000000..a705908a203c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_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 alloydb_v1alpha + + +async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_sync.py new file mode 100644 index 000000000000..7e4576f9a3c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_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 alloydb_v1alpha + + +def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_async.py new file mode 100644 index 000000000000..b553c1a89a10 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +async def sample_get_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_sync.py new file mode 100644 index 000000000000..f1d4d926f941 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +def sample_get_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_async.py new file mode 100644 index 000000000000..87ba9b1320e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1alpha + + +async def sample_get_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_sync.py new file mode 100644 index 000000000000..fdf9eff4808a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1alpha + + +def sample_get_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_async.py new file mode 100644 index 000000000000..dd1a73686847 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_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 alloydb_v1alpha + + +async def sample_get_connection_info(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_sync.py new file mode 100644 index 000000000000..67fc0358000c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_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 alloydb_v1alpha + + +def sample_get_connection_info(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_async.py new file mode 100644 index 000000000000..b8263acfc8de --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1alpha + + +async def sample_get_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_sync.py new file mode 100644 index 000000000000..11e38cea1530 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1alpha + + +def sample_get_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_async.py new file mode 100644 index 000000000000..aa121f16a5a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_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 alloydb_v1alpha + + +async def sample_get_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_sync.py new file mode 100644 index 000000000000..79e3142a8439 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_get_user_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_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 alloydb_v1alpha + + +def sample_get_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_async.py new file mode 100644 index 000000000000..29e0bd6279e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1alpha + + +async def sample_inject_fault(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_sync.py new file mode 100644 index 000000000000..402b639ccf07 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_inject_fault_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1alpha + + +def sample_inject_fault(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_async.py new file mode 100644 index 000000000000..9149300dfe9a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +async def sample_list_backups(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1alpha_generated_AlloyDBAdmin_ListBackups_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_sync.py new file mode 100644 index 000000000000..ef943bad60fd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_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 alloydb_v1alpha + + +def sample_list_backups(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1alpha_generated_AlloyDBAdmin_ListBackups_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_async.py new file mode 100644 index 000000000000..3c73038e28ba --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1alpha + + +async def sample_list_clusters(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_sync.py new file mode 100644 index 000000000000..d7756ef06560 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1alpha + + +def sample_list_clusters(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_async.py new file mode 100644 index 000000000000..af000e64ee6c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1alpha + + +async def sample_list_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_sync.py new file mode 100644 index 000000000000..6209c304c099 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1alpha + + +def sample_list_instances(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_async.py new file mode 100644 index 000000000000..b9d9e7441073 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1alpha + + +async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_sync.py new file mode 100644 index 000000000000..ecbef3afcf54 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1alpha + + +def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_async.py new file mode 100644 index 000000000000..78ea4f233dd2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1alpha + + +async def sample_list_users(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_sync.py new file mode 100644 index 000000000000..065c51123062 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_list_users_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1alpha + + +def sample_list_users(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_async.py new file mode 100644 index 000000000000..d754e209f6c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1alpha + + +async def sample_promote_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_sync.py new file mode 100644 index 000000000000..14258a86eab9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1alpha + + +def sample_promote_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_async.py new file mode 100644 index 000000000000..116f3d44adf5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1alpha + + +async def sample_restart_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_sync.py new file mode 100644 index 000000000000..781900db43c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restart_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1alpha + + +def sample_restart_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_async.py new file mode 100644 index 000000000000..d3b88ea33f1b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1alpha + + +async def sample_restore_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1alpha.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_sync.py new file mode 100644 index 000000000000..252a791d4bc0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1alpha + + +def sample_restore_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1alpha.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_async.py new file mode 100644 index 000000000000..c716c0b35a5c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1alpha + + +async def sample_update_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_sync.py new file mode 100644 index 000000000000..b83eb7931f3f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_backup_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1alpha + + +def sample_update_backup(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1alpha.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1alpha.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_async.py new file mode 100644 index 000000000000..83fcaeebd4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1alpha + + +async def sample_update_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_sync.py new file mode 100644 index 000000000000..55ce3eb6d96d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_cluster_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1alpha + + +def sample_update_cluster(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1alpha.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1alpha.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_async.py new file mode 100644 index 000000000000..7166b33d3d5d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1alpha + + +async def sample_update_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_sync.py new file mode 100644 index 000000000000..872260e1ce17 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_instance_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1alpha + + +def sample_update_instance(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1alpha.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1alpha.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_async.py new file mode 100644 index 000000000000..8e44a5da2d00 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1alpha + + +async def sample_update_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_sync.py new file mode 100644 index 000000000000..5da0399941bd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/alloydb_v1alpha_generated_alloy_db_admin_update_user_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1alpha + + +def sample_update_user(): + # Create a client + client = alloydb_v1alpha.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1alpha.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json new file mode 100644 index 000000000000..53090fc16662 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json @@ -0,0 +1,5120 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.alloydb.v1alpha", + "version": "v1alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-alloydb", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_BatchCreateInstances_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_batch_create_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1alpha_generated_alloy_db_admin_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateBackup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1alpha_generated_alloy_db_admin_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateBackup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateSecondaryInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_secondary_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1alpha.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1alpha.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1alpha.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1alpha.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_CreateUser_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_DeleteUser_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_failover_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_failover_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_failover_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_failover_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GenerateClientCertificateRequest" + }, + { + "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.alloydb_v1alpha.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_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": "alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GenerateClientCertificateRequest" + }, + { + "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.alloydb_v1alpha.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GenerateClientCertificate_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": "alloydb_v1alpha_generated_alloy_db_admin_generate_client_certificate_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1alpha.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1alpha.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetClusterRequest" + }, + { + "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.alloydb_v1alpha.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_get_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetClusterRequest" + }, + { + "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.alloydb_v1alpha.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_get_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetConnectionInfoRequest" + }, + { + "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.alloydb_v1alpha.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_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": "alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetConnectionInfoRequest" + }, + { + "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.alloydb_v1alpha.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetConnectionInfo_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": "alloydb_v1alpha_generated_alloy_db_admin_get_connection_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetInstanceRequest" + }, + { + "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.alloydb_v1alpha.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetInstanceRequest" + }, + { + "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.alloydb_v1alpha.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetUserRequest" + }, + { + "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.alloydb_v1alpha.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1alpha_generated_alloy_db_admin_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.GetUserRequest" + }, + { + "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.alloydb_v1alpha.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1alpha_generated_alloy_db_admin_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1alpha.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1alpha_generated_alloy_db_admin_inject_fault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1alpha_generated_alloy_db_admin_inject_fault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1alpha.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1alpha_generated_alloy_db_admin_inject_fault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1alpha_generated_alloy_db_admin_inject_fault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_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": "alloydb_v1alpha_generated_alloy_db_admin_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListClustersRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListClustersAsyncPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1alpha_generated_alloy_db_admin_list_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListClustersRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListClustersPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1alpha_generated_alloy_db_admin_list_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListInstancesRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1alpha_generated_alloy_db_admin_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListInstancesRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1alpha_generated_alloy_db_admin_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1alpha_generated_alloy_db_admin_list_supported_database_flags_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListUsersRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1alpha_generated_alloy_db_admin_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.ListUsersRequest" + }, + { + "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.alloydb_v1alpha.services.alloy_db_admin.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1alpha_generated_alloy_db_admin_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1alpha_generated_alloy_db_admin_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1alpha_generated_alloy_db_admin_promote_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_restart_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_restart_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_restart_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_restart_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_RestoreCluster_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_restore_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1alpha.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1alpha_generated_alloy_db_admin_update_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1alpha.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1alpha_generated_alloy_db_admin_update_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_update_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1alpha.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateCluster_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_update_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_update_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1alpha.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1alpha_generated_alloy_db_admin_update_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminAsyncClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1alpha.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1alpha.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1alpha.AlloyDBAdminClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1alpha.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1alpha.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1alpha.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1alpha.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1alpha_generated_alloy_db_admin_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1alpha_generated_AlloyDBAdmin_UpdateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1alpha_generated_alloy_db_admin_update_user_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/scripts/fixup_alloydb_v1alpha_keywords.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/scripts/fixup_alloydb_v1alpha_keywords.py new file mode 100644 index 000000000000..14b3ca7826ae --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/scripts/fixup_alloydb_v1alpha_keywords.py @@ -0,0 +1,206 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class alloydbCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_instances': ('parent', 'requests', 'request_id', ), + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', 'validate_only', ), + 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_secondary_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_secondary_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_user': ('parent', 'user_id', 'user', 'request_id', 'validate_only', ), + 'delete_backup': ('name', 'request_id', 'validate_only', 'etag', ), + 'delete_cluster': ('name', 'request_id', 'etag', 'validate_only', 'force', ), + 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), + 'delete_user': ('name', 'request_id', 'validate_only', ), + 'failover_instance': ('name', 'request_id', 'validate_only', ), + 'generate_client_certificate': ('parent', 'request_id', 'pem_csr', 'cert_duration', 'public_key', 'use_metadata_exchange', ), + 'get_backup': ('name', ), + 'get_cluster': ('name', 'view', ), + 'get_connection_info': ('parent', 'request_id', ), + 'get_instance': ('name', 'view', ), + 'get_user': ('name', ), + 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_supported_database_flags': ('parent', 'page_size', 'page_token', ), + 'list_users': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'promote_cluster': ('name', 'request_id', 'etag', 'validate_only', ), + 'restart_instance': ('name', 'request_id', 'validate_only', ), + 'restore_cluster': ('parent', 'cluster_id', 'cluster', 'backup_source', 'continuous_backup_source', 'request_id', 'validate_only', ), + 'update_backup': ('backup', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_cluster': ('cluster', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_instance': ('instance', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_user': ('user', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + } + + 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=alloydbCallTransformer(), +): + """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 alloydb client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/setup.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/setup.py new file mode 100644 index 000000000000..4c8aa9156a9f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-alloydb' + + +description = "Google Cloud Alloydb API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/alloydb/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-alloydb" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2beecf99e0be --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-alloydb/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1alpha/tests/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py new file mode 100644 index 000000000000..6c22c67408dd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1alpha/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py @@ -0,0 +1,18480 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.alloydb_v1alpha.services.alloy_db_admin import AlloyDBAdminAsyncClient +from google.cloud.alloydb_v1alpha.services.alloy_db_admin import AlloyDBAdminClient +from google.cloud.alloydb_v1alpha.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1alpha.services.alloy_db_admin import transports +from google.cloud.alloydb_v1alpha.types import resources +from google.cloud.alloydb_v1alpha.types import service +from google.cloud.location import locations_pb2 +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 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +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.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_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 AlloyDBAdminClient._get_default_mtls_endpoint(None) is None + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AlloyDBAdminGrpcTransport, "grpc"), + (transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +def test_alloy_db_admin_client_get_transport_class(): + transport = AlloyDBAdminClient.get_transport_class() + available_transports = [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminRestTransport, + ] + assert transport in available_transports + + transport = AlloyDBAdminClient.get_transport_class("grpc") + assert transport == transports.AlloyDBAdminGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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(AlloyDBAdminClient, '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(AlloyDBAdminClient, '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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "true"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "false"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "false"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_alloy_db_admin_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", [ + AlloyDBAdminClient, AlloyDBAdminAsyncClient +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", None), +]) +def test_alloy_db_admin_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_alloy_db_admin_client_client_options_from_dict(): + with mock.patch('google.cloud.alloydb_v1alpha.services.alloy_db_admin.transports.AlloyDBAdminGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_clusters), + '__call__') as call: + client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + +@pytest.mark.asyncio +async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=service.ListClustersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_clusters_async_from_dict(): + await test_list_clusters_async(request_type=dict) + + +def test_list_clusters_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = service.ListClustersResponse() + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_clusters_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_clusters_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_clusters( + 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_clusters_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_clusters_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_clusters( + 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_clusters_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) +def test_list_clusters_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clusters(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_clusters_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clusters(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Cluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_clusters_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + satisfies_pzs=True, + ) + response = client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + assert response.satisfies_pzs is True + + +def test_get_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + +@pytest.mark.asyncio +async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=service.GetClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + satisfies_pzs=True, + )) + response = await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_get_cluster_async_from_dict(): + await test_get_cluster_async(request_type=dict) + + +def test_get_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = resources.Cluster() + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + +@pytest.mark.asyncio +async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_cluster_async_from_dict(): + await test_create_cluster_async(request_type=dict) + + +def test_create_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + +@pytest.mark.asyncio +async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_cluster_async_from_dict(): + await test_update_cluster_async(request_type=dict) + + +def test_update_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + +@pytest.mark.asyncio +async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_cluster_async_from_dict(): + await test_delete_cluster_async(request_type=dict) + + +def test_delete_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_promote_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + client.promote_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + +@pytest.mark.asyncio +async def test_promote_cluster_async(transport: str = 'grpc_asyncio', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_promote_cluster_async_from_dict(): + await test_promote_cluster_async(request_type=dict) + + +def test_promote_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_promote_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_promote_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_promote_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.restore_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + +@pytest.mark.asyncio +async def test_restore_cluster_async(transport: str = 'grpc_asyncio', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_cluster_async_from_dict(): + await test_restore_cluster_async(request_type=dict) + + +def test_restore_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_restore_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_cluster), + '__call__') as call: + client.create_secondary_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__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_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async_from_dict(): + await test_create_secondary_cluster_async(request_type=dict) + + +def test_create_secondary_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_secondary_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instances), + '__call__') as call: + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=service.ListInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = service.ListInstancesResponse() + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instances_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + 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_instances_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + 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_instances_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) +def test_list_instances_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Instance) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + satisfies_pzs=True, + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.satisfies_pzs is True + + +def test_get_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=service.GetInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + satisfies_pzs=True, + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.satisfies_pzs is True + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = resources.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.create_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + +@pytest.mark.asyncio +async def test_create_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_instance), + '__call__') as call: + client.create_secondary_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + +@pytest.mark.asyncio +async def test_create_secondary_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__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_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_instance_async_from_dict(): + await test_create_secondary_instance_async(request_type=dict) + + +def test_create_secondary_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_secondary_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_create_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + client.batch_create_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + +@pytest.mark.asyncio +async def test_batch_create_instances_async(transport: str = 'grpc_asyncio', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__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.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_create_instances_async_from_dict(): + await test_batch_create_instances_async(request_type=dict) + + +def test_batch_create_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.update_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + +@pytest.mark.asyncio +async def test_update_instance_async(transport: str = 'grpc_asyncio', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_instance_async_from_dict(): + await test_update_instance_async(request_type=dict) + + +def test_update_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +def test_update_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + +@pytest.mark.asyncio +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_failover_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + client.failover_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + +@pytest.mark.asyncio +async def test_failover_instance_async(transport: str = 'grpc_asyncio', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_failover_instance_async_from_dict(): + await test_failover_instance_async(request_type=dict) + + +def test_failover_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_failover_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_failover_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_failover_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_inject_fault_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + client.inject_fault() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + +@pytest.mark.asyncio +async def test_inject_fault_async(transport: str = 'grpc_asyncio', request_type=service.InjectFaultRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_inject_fault_async_from_dict(): + await test_inject_fault_async(request_type=dict) + + +def test_inject_fault_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_inject_fault_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_inject_fault_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_inject_fault_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + +@pytest.mark.asyncio +async def test_inject_fault_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_inject_fault_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restart_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + client.restart_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + +@pytest.mark.asyncio +async def test_restart_instance_async(transport: str = 'grpc_asyncio', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restart_instance_async_from_dict(): + await test_restart_instance_async(request_type=dict) + + +def test_restart_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_restart_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_restart_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_restart_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = service.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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=service.ListBackupsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(service.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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(service.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 = AlloyDBAdminClient( + 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 = service.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 = AlloyDBAdminClient( + credentials=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( + service.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = service.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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 = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_backups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + satisfies_pzs=True, + ) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.satisfies_pzs is True + + +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 = AlloyDBAdminClient( + credentials=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] == service.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=service.GetBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + satisfies_pzs=True, + )) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.satisfies_pzs is True + + +@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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(resources.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 = AlloyDBAdminClient( + 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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = resources.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=service.CreateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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=resources.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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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=resources.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_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] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_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 = AlloyDBAdminClient( + credentials=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_backup), + '__call__') as call: + client.update_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + +@pytest.mark.asyncio +async def test_update_backup_async(transport: str = 'grpc_asyncio', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_backup_async_from_dict(): + await test_update_backup_async(request_type=dict) + + +def test_update_backup_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_backup_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +def test_update_backup_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=service.DeleteBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=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( + service.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_supported_database_flags), + '__call__') as call: + client.list_supported_database_flags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async(transport: str = 'grpc_asyncio', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_from_dict(): + await test_list_supported_database_flags_async(request_type=dict) + + +def test_list_supported_database_flags_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = service.ListSupportedDatabaseFlagsResponse() + client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_supported_database_flags_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_supported_database_flags_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_supported_database_flags( + 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_supported_database_flags_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_supported_database_flags_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_supported_database_flags( + 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_supported_database_flags_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_supported_database_flags(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) +def test_list_supported_database_flags_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_supported_database_flags(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_supported_database_flags_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_supported_database_flags(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_supported_database_flags(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GenerateClientCertificateRequest, + dict, +]) +def test_generate_client_certificate(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + ) + response = client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +def test_generate_client_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + client.generate_client_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + +@pytest.mark.asyncio +async def test_generate_client_certificate_async(transport: str = 'grpc_asyncio', request_type=service.GenerateClientCertificateRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + )) + response = await client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +@pytest.mark.asyncio +async def test_generate_client_certificate_async_from_dict(): + await test_generate_client_certificate_async(request_type=dict) + + +def test_generate_client_certificate_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateClientCertificateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + call.return_value = service.GenerateClientCertificateResponse() + client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_generate_client_certificate_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateClientCertificateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse()) + await client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_generate_client_certificate_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_client_certificate( + 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_generate_client_certificate_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_generate_client_certificate_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_client_certificate( + 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_generate_client_certificate_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetConnectionInfoRequest, + dict, +]) +def test_get_connection_info(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + ) + response = client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +def test_get_connection_info_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_connection_info), + '__call__') as call: + client.get_connection_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + +@pytest.mark.asyncio +async def test_get_connection_info_async(transport: str = 'grpc_asyncio', request_type=service.GetConnectionInfoRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + )) + response = await client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +@pytest.mark.asyncio +async def test_get_connection_info_async_from_dict(): + await test_get_connection_info_async(request_type=dict) + + +def test_get_connection_info_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + call.return_value = resources.ConnectionInfo() + client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_connection_info_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo()) + await client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_connection_info_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_connection_info( + 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_get_connection_info_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_get_connection_info_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_connection_info( + 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_get_connection_info_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListUsersRequest, + dict, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_users), + '__call__') as call: + client.list_users() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + +@pytest.mark.asyncio +async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=service.ListUsersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) + + +def test_list_users_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = service.ListUsersResponse() + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_users_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_users_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + 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_users_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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_users_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_users(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetUserRequest, + dict, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.get_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + +@pytest.mark.asyncio +async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=service.GetUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + + +def test_get_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = resources.User() + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.create_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + +@pytest.mark.asyncio +async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=service.CreateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) + + +def test_create_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = resources.User() + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.update_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + +@pytest.mark.asyncio +async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=service.UpdateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + + +def test_update_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = resources.User() + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +def test_update_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.delete_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + +@pytest.mark.asyncio +async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=service.DeleteUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + + +def test_delete_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListClustersResponse( + 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 = service.ListClustersResponse.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_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_clusters._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_clusters._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListClustersResponse.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_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_clusters._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_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_clusters") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json(service.ListClustersResponse()) + + request = service.ListClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request(transport: str = 'rest', request_type=service.ListClustersRequest): + client = AlloyDBAdminClient( + 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_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + + # 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 = service.ListClustersResponse.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_clusters(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_list_clusters_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.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_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) + + pages = list(client.list_clusters(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", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + satisfies_pzs=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.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_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + assert response.satisfies_pzs is True + + +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Cluster.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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + + request = service.GetClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Cluster() + + client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request(transport: str = 'rest', request_type=service.GetClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/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 = resources.Cluster.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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_get_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_cluster(request) + + +def test_create_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_create_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_cluster_rest_bad_request(transport: str = 'rest', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster(**mock_args) + + # Establish that the underlying call 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/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_update_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request(transport: str = 'rest', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_delete_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +def test_delete_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_promote_cluster_rest_required_fields(request_type=service.PromoteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).promote_cluster._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()).promote_cluster._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 = AlloyDBAdminClient( + 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.promote_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_promote_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_promote_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_promote_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.PromoteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.promote_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_promote_cluster_rest_bad_request(transport: str = 'rest', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + +def test_promote_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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.promote_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}:promote" % client.transport._host, args[1]) + + +def test_promote_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +def test_promote_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster_rest(request_type): + client = AlloyDBAdminClient( + 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 = 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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_cluster_rest_required_fields(request_type=service.RestoreClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restore_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestoreClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_cluster_rest_bad_request(transport: str = 'rest', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminClient( + 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.restore_cluster(request) + + +def test_restore_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_secondary_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_cluster_rest_required_fields(request_type=service.CreateSecondaryClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_secondary_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryClusterRequest.pb(service.CreateSecondaryClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_value2']}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_secondary_cluster(request) + + +def test_create_secondary_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_secondary_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_secondary_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse( + 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 = service.ListInstancesResponse.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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instances._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_instances._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListInstancesResponse.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_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_instances._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_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListInstancesResponse.to_json(service.ListInstancesResponse()) + + request = service.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request(transport: str = 'rest', request_type=service.ListInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_instances(request) + + +def test_list_instances_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse.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_instances(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_list_instances_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.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/clusters/sample3'} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) + + pages = list(client.list_instances(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", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + satisfies_pzs=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Instance.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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.satisfies_pzs is True + + +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Instance.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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Instance.to_json(resources.Instance()) + + request = service.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=service.GetInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_get_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance.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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_instance_rest_required_fields(request_type=service.CreateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_instance(request) + + +def test_create_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_create_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_secondary_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_instance_rest_required_fields(request_type=service.CreateSecondaryInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_secondary_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryInstanceRequest.pb(service.CreateSecondaryInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_secondary_instance(request) + + +def test_create_secondary_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_secondary_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_secondary_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and 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.batch_create_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_create_instances_rest_required_fields(request_type=service.BatchCreateInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).batch_create_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + 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.batch_create_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_batch_create_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.BatchCreateInstancesRequest.pb(service.BatchCreateInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.BatchCreateInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_create_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_instances_rest_bad_request(transport: str = 'rest', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_instances(request) + + +def test_batch_create_instances_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_instance_rest_required_fields(request_type=service.UpdateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request(transport: str = 'rest', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_instance(request) + + +def test_update_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + instance=resources.Instance(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_instance(**mock_args) + + # Establish that the underlying call 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_update_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_instance_rest_required_fields(request_type=service.DeleteInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request(transport: str = 'rest', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_delete_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_delete_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +def test_delete_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_failover_instance_rest_required_fields(request_type=service.FailoverInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).failover_instance._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()).failover_instance._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 = AlloyDBAdminClient( + 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.failover_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_failover_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_failover_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_failover_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_failover_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FailoverInstanceRequest.pb(service.FailoverInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.FailoverInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.failover_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_failover_instance_rest_bad_request(transport: str = 'rest', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + +def test_failover_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.failover_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:failover" % client.transport._host, args[1]) + + +def test_failover_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +def test_failover_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).inject_fault._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()).inject_fault._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 = AlloyDBAdminClient( + 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.inject_fault(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_inject_fault_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.inject_fault._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("faultType", "name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_inject_fault_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_inject_fault") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_inject_fault") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.InjectFaultRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.inject_fault(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_inject_fault_rest_bad_request(transport: str = 'rest', request_type=service.InjectFaultRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + +def test_inject_fault_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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.inject_fault(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1]) + + +def test_inject_fault_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +def test_inject_fault_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restart_instance_rest_required_fields(request_type=service.RestartInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).restart_instance._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()).restart_instance._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 = AlloyDBAdminClient( + 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.restart_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restart_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restart_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restart_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restart_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restart_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestartInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restart_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restart_instance_rest_bad_request(transport: str = 'rest', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + +def test_restart_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.restart_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:restart" % client.transport._host, args[1]) + + +def test_restart_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +def test_restart_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.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 = service.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=service.ListBackupsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.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 = service.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListBackupsRequest.pb(service.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 = service.ListBackupsResponse.to_json(service.ListBackupsResponse()) + + request = service.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.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=service.ListBackupsRequest): + client = AlloyDBAdminClient( + 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_backups(request) + + +def test_list_backups_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListBackupsResponse() + + # 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 = service.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/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.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'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.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", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + satisfies_pzs=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.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, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.satisfies_pzs is True + + +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.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 = resources.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetBackupRequest.pb(service.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 = resources.Backup.to_json(resources.Backup()) + + request = service.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.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=service.GetBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/backups/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 = resources.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/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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=service.CreateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", "validateOnly", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateBackupRequest.pb(service.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 = service.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=service.CreateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + backup=resources.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/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_backup._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_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_backup_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_backup_rest_bad_request(transport: str = 'rest', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'satisfies_pzs': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_backup(request) + + +def test_update_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + backup=resources.Backup(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_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/{backup.name=projects/*/locations/*/backups/*}" % client.transport._host, args[1]) + + +def test_update_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_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=service.DeleteBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteBackupRequest.pb(service.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 = service.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=service.DeleteBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_delete_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/backups/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_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/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_rest_required_fields(request_type=service.ListSupportedDatabaseFlagsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_supported_database_flags._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_supported_database_flags._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_supported_database_flags_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_supported_database_flags._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_supported_database_flags_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListSupportedDatabaseFlagsRequest.pb(service.ListSupportedDatabaseFlagsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json(service.ListSupportedDatabaseFlagsResponse()) + + request = service.ListSupportedDatabaseFlagsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListSupportedDatabaseFlagsResponse() + + client.list_supported_database_flags(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_supported_database_flags_rest_bad_request(transport: str = 'rest', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminClient( + 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_supported_database_flags(request) + + +def test_list_supported_database_flags_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + + # 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(**mock_args) + + # Establish that the underlying call 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/*}/supportedDatabaseFlags" % client.transport._host, args[1]) + + +def test_list_supported_database_flags_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) + + pages = list(client.list_supported_database_flags(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", [ + service.GenerateClientCertificateRequest, + dict, +]) +def test_generate_client_certificate_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.GenerateClientCertificateResponse.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.generate_client_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +def test_generate_client_certificate_rest_required_fields(request_type=service.GenerateClientCertificateRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).generate_client_certificate._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()).generate_client_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateClientCertificateResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.GenerateClientCertificateResponse.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.generate_client_certificate(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_client_certificate_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_client_certificate_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateClientCertificateRequest.pb(service.GenerateClientCertificateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.GenerateClientCertificateResponse.to_json(service.GenerateClientCertificateResponse()) + + request = service.GenerateClientCertificateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateClientCertificateResponse() + + client.generate_client_certificate(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_client_certificate_rest_bad_request(transport: str = 'rest', request_type=service.GenerateClientCertificateRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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.generate_client_certificate(request) + + +def test_generate_client_certificate_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateClientCertificateResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.GenerateClientCertificateResponse.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.generate_client_certificate(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}:generateClientCertificate" % client.transport._host, args[1]) + + +def test_generate_client_certificate_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + + +def test_generate_client_certificate_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetConnectionInfoRequest, + dict, +]) +def test_get_connection_info_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ConnectionInfo.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_connection_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +def test_get_connection_info_rest_required_fields(request_type=service.GetConnectionInfoRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).get_connection_info._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()).get_connection_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConnectionInfo() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.ConnectionInfo.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_connection_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_connection_info_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_connection_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connection_info_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_connection_info") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetConnectionInfoRequest.pb(service.GetConnectionInfoRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.ConnectionInfo.to_json(resources.ConnectionInfo()) + + request = service.GetConnectionInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConnectionInfo() + + client.get_connection_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_connection_info_rest_bad_request(transport: str = 'rest', request_type=service.GetConnectionInfoRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_connection_info(request) + + +def test_get_connection_info_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConnectionInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'} + + # 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 = resources.ConnectionInfo.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_connection_info(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}/connectionInfo" % client.transport._host, args[1]) + + +def test_get_connection_info_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + + +def test_get_connection_info_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListUsersRequest, + dict, +]) +def test_list_users_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse( + 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 = service.ListUsersResponse.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_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_users._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_users._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListUsersResponse.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_users(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_users_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_users._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_users_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListUsersRequest.pb(service.ListUsersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListUsersResponse.to_json(service.ListUsersResponse()) + + request = service.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListUsersResponse() + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_users_rest_bad_request(transport: str = 'rest', request_type=service.ListUsersRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_users(request) + + +def test_list_users_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse.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_users(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_list_users_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListUsersResponse.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/clusters/sample3'} + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) + + pages = list(client.list_users(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", [ + service.GetUserRequest, + dict, +]) +def test_get_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.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_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_rest_required_fields(request_type=service.GetUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.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_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetUserRequest.pb(service.GetUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_rest_bad_request(transport: str = 'rest', request_type=service.GetUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_get_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User.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_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.GetUserRequest(), + name='name_value', + ) + + +def test_get_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_rest_required_fields(request_type=service.CreateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_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 "userId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userId"] = 'user_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._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", "user_id", "validate_only", )) + 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 "userId" in jsonified_request + assert jsonified_request["userId"] == 'user_id_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_user(request) + + expected_params = [ + ( + "userId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "userId", "validateOnly", )) & set(("parent", "userId", "user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateUserRequest.pb(service.CreateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_rest_bad_request(transport: str = 'rest', request_type=service.CreateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_create_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +def test_create_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateUserRequest.pb(service.UpdateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_rest_bad_request(transport: str = 'rest', request_type=service.UpdateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_update_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_user(**mock_args) + + # Establish that the underlying call 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/{user.name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_update_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = 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_user(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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", "validate_only", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = service.DeleteUserRequest.pb(service.DeleteUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = service.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_user_rest_bad_request(transport: str = 'rest', request_type=service.DeleteUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_delete_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +def test_delete_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AlloyDBAdminClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, +]) +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 = AlloyDBAdminClient.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AlloyDBAdminGrpcTransport, + ) + +def test_alloy_db_admin_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_alloy_db_admin_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.alloydb_v1alpha.services.alloy_db_admin.transports.AlloyDBAdminTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_clusters', + 'get_cluster', + 'create_cluster', + 'update_cluster', + 'delete_cluster', + 'promote_cluster', + 'restore_cluster', + 'create_secondary_cluster', + 'list_instances', + 'get_instance', + 'create_instance', + 'create_secondary_instance', + 'batch_create_instances', + 'update_instance', + 'delete_instance', + 'failover_instance', + 'inject_fault', + 'restart_instance', + 'list_backups', + 'get_backup', + 'create_backup', + 'update_backup', + 'delete_backup', + 'list_supported_database_flags', + 'generate_client_certificate', + 'get_connection_info', + 'list_users', + 'get_user', + 'create_user', + 'update_user', + 'delete_user', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # 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_alloy_db_admin_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.alloydb_v1alpha.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport( + 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_alloy_db_admin_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.alloydb_v1alpha.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport() + adc.assert_called_once() + + +def test_alloy_db_admin_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) + AlloyDBAdminClient() + 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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, grpc_helpers), + (transports.AlloyDBAdminGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_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.AlloyDBAdminRestTransport ( + 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_alloy_db_admin_rest_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_host_no_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_alloy_db_admin_host_with_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_alloy_db_admin_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AlloyDBAdminClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AlloyDBAdminClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.promote_cluster._session + session2 = client2.transport.promote_cluster._session + assert session1 != session2 + session1 = client1.transport.restore_cluster._session + session2 = client2.transport.restore_cluster._session + assert session1 != session2 + session1 = client1.transport.create_secondary_cluster._session + session2 = client2.transport.create_secondary_cluster._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.create_secondary_instance._session + session2 = client2.transport.create_secondary_instance._session + assert session1 != session2 + session1 = client1.transport.batch_create_instances._session + session2 = client2.transport.batch_create_instances._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.failover_instance._session + session2 = client2.transport.failover_instance._session + assert session1 != session2 + session1 = client1.transport.inject_fault._session + session2 = client2.transport.inject_fault._session + assert session1 != session2 + session1 = client1.transport.restart_instance._session + session2 = client2.transport.restart_instance._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.update_backup._session + session2 = client2.transport.update_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.list_supported_database_flags._session + session2 = client2.transport.list_supported_database_flags._session + assert session1 != session2 + session1 = client1.transport.generate_client_certificate._session + session2 = client2.transport.generate_client_certificate._session + assert session1 != session2 + session1 = client1.transport.get_connection_info._session + session2 = client2.transport.get_connection_info._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 +def test_alloy_db_admin_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcTransport( + 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_alloy_db_admin_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + 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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_grpc_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_grpc_lro_async_client(): + client = AlloyDBAdminAsyncClient( + 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" + backup = "whelk" + expected = "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, backup=backup, ) + actual = AlloyDBAdminClient.backup_path(project, location, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "octopus", + "location": "oyster", + "backup": "nudibranch", + } + path = AlloyDBAdminClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_backup_path(path) + assert expected == actual + +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = AlloyDBAdminClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = AlloyDBAdminClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_cluster_path(path) + assert expected == actual + +def test_connection_info_path(): + project = "squid" + location = "clam" + cluster = "whelk" + instance = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format(project=project, location=location, cluster=cluster, instance=instance, ) + actual = AlloyDBAdminClient.connection_info_path(project, location, cluster, instance) + assert expected == actual + + +def test_parse_connection_info_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "instance": "mussel", + } + path = AlloyDBAdminClient.connection_info_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_connection_info_path(path) + assert expected == actual + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = AlloyDBAdminClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = AlloyDBAdminClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_crypto_key_version_path(path) + assert expected == actual + +def test_instance_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + instance = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + actual = AlloyDBAdminClient.instance_path(project, location, cluster, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "instance": "clam", + } + path = AlloyDBAdminClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_instance_path(path) + assert expected == actual + +def test_network_path(): + project = "whelk" + network = "octopus" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = AlloyDBAdminClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "oyster", + "network": "nudibranch", + } + path = AlloyDBAdminClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_network_path(path) + assert expected == actual + +def test_supported_database_flag_path(): + project = "cuttlefish" + location = "mussel" + flag = "winkle" + expected = "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + actual = AlloyDBAdminClient.supported_database_flag_path(project, location, flag) + assert expected == actual + + +def test_parse_supported_database_flag_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "flag": "abalone", + } + path = AlloyDBAdminClient.supported_database_flag_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_supported_database_flag_path(path) + assert expected == actual + +def test_user_path(): + project = "squid" + location = "clam" + cluster = "whelk" + user = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + actual = AlloyDBAdminClient.user_path(project, location, cluster, user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "user": "mussel", + } + path = AlloyDBAdminClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AlloyDBAdminClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = AlloyDBAdminClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = AlloyDBAdminClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = AlloyDBAdminClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AlloyDBAdminClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = AlloyDBAdminClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = AlloyDBAdminClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = AlloyDBAdminClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.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 = AlloyDBAdminClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = AlloyDBAdminClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.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.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + transport_class = AlloyDBAdminClient.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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport), +]) +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/google-cloud-alloydb/v1beta/.coveragerc b/owl-bot-staging/google-cloud-alloydb/v1beta/.coveragerc new file mode 100644 index 000000000000..307a1b7e14a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/alloydb/__init__.py + google/cloud/alloydb/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/.flake8 b/owl-bot-staging/google-cloud-alloydb/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-alloydb/v1beta/MANIFEST.in new file mode 100644 index 000000000000..aa20ee3df6c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/alloydb *.py +recursive-include google/cloud/alloydb_v1beta *.py diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/README.rst b/owl-bot-staging/google-cloud-alloydb/v1beta/README.rst new file mode 100644 index 000000000000..6a459d0a64f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Alloydb 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 Alloydb API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/alloy_db_admin.rst b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/alloy_db_admin.rst new file mode 100644 index 000000000000..2998426115e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/alloy_db_admin.rst @@ -0,0 +1,10 @@ +AlloyDBAdmin +------------------------------ + +.. automodule:: google.cloud.alloydb_v1beta.services.alloy_db_admin + :members: + :inherited-members: + +.. automodule:: google.cloud.alloydb_v1beta.services.alloy_db_admin.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/services.rst b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/services.rst new file mode 100644 index 000000000000..f0f4f416e44f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Alloydb v1beta API +============================================ +.. toctree:: + :maxdepth: 2 + + alloy_db_admin diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/types.rst b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/types.rst new file mode 100644 index 000000000000..979a4ec6e43a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/alloydb_v1beta/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Alloydb v1beta API +========================================= + +.. automodule:: google.cloud.alloydb_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/conf.py new file mode 100644 index 000000000000..16113c8bdd60 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-alloydb 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-alloydb" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-alloydb-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-alloydb.tex", + u"google-cloud-alloydb 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-alloydb", + u"Google Cloud Alloydb 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-alloydb", + u"google-cloud-alloydb Documentation", + author, + "google-cloud-alloydb", + "GAPIC library for Google Cloud Alloydb API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/index.rst new file mode 100644 index 000000000000..938b45373dc3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + alloydb_v1beta/services + alloydb_v1beta/types diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/__init__.py new file mode 100644 index 000000000000..b395e0b1a37c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/__init__.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.alloydb_v1beta.services.alloy_db_admin.client import AlloyDBAdminClient +from google.cloud.alloydb_v1beta.services.alloy_db_admin.async_client import AlloyDBAdminAsyncClient + +from google.cloud.alloydb_v1beta.types.resources import AutomatedBackupPolicy +from google.cloud.alloydb_v1beta.types.resources import Backup +from google.cloud.alloydb_v1beta.types.resources import BackupSource +from google.cloud.alloydb_v1beta.types.resources import Cluster +from google.cloud.alloydb_v1beta.types.resources import ConnectionInfo +from google.cloud.alloydb_v1beta.types.resources import ContinuousBackupConfig +from google.cloud.alloydb_v1beta.types.resources import ContinuousBackupInfo +from google.cloud.alloydb_v1beta.types.resources import ContinuousBackupSource +from google.cloud.alloydb_v1beta.types.resources import EncryptionConfig +from google.cloud.alloydb_v1beta.types.resources import EncryptionInfo +from google.cloud.alloydb_v1beta.types.resources import Instance +from google.cloud.alloydb_v1beta.types.resources import MigrationSource +from google.cloud.alloydb_v1beta.types.resources import SslConfig +from google.cloud.alloydb_v1beta.types.resources import SupportedDatabaseFlag +from google.cloud.alloydb_v1beta.types.resources import User +from google.cloud.alloydb_v1beta.types.resources import UserPassword +from google.cloud.alloydb_v1beta.types.resources import ClusterView +from google.cloud.alloydb_v1beta.types.resources import DatabaseVersion +from google.cloud.alloydb_v1beta.types.resources import InstanceView +from google.cloud.alloydb_v1beta.types.service import BatchCreateInstancesMetadata +from google.cloud.alloydb_v1beta.types.service import BatchCreateInstancesRequest +from google.cloud.alloydb_v1beta.types.service import BatchCreateInstancesResponse +from google.cloud.alloydb_v1beta.types.service import BatchCreateInstanceStatus +from google.cloud.alloydb_v1beta.types.service import CreateBackupRequest +from google.cloud.alloydb_v1beta.types.service import CreateClusterRequest +from google.cloud.alloydb_v1beta.types.service import CreateInstanceRequest +from google.cloud.alloydb_v1beta.types.service import CreateInstanceRequests +from google.cloud.alloydb_v1beta.types.service import CreateSecondaryClusterRequest +from google.cloud.alloydb_v1beta.types.service import CreateSecondaryInstanceRequest +from google.cloud.alloydb_v1beta.types.service import CreateUserRequest +from google.cloud.alloydb_v1beta.types.service import DeleteBackupRequest +from google.cloud.alloydb_v1beta.types.service import DeleteClusterRequest +from google.cloud.alloydb_v1beta.types.service import DeleteInstanceRequest +from google.cloud.alloydb_v1beta.types.service import DeleteUserRequest +from google.cloud.alloydb_v1beta.types.service import FailoverInstanceRequest +from google.cloud.alloydb_v1beta.types.service import GenerateClientCertificateRequest +from google.cloud.alloydb_v1beta.types.service import GenerateClientCertificateResponse +from google.cloud.alloydb_v1beta.types.service import GetBackupRequest +from google.cloud.alloydb_v1beta.types.service import GetClusterRequest +from google.cloud.alloydb_v1beta.types.service import GetConnectionInfoRequest +from google.cloud.alloydb_v1beta.types.service import GetInstanceRequest +from google.cloud.alloydb_v1beta.types.service import GetUserRequest +from google.cloud.alloydb_v1beta.types.service import InjectFaultRequest +from google.cloud.alloydb_v1beta.types.service import ListBackupsRequest +from google.cloud.alloydb_v1beta.types.service import ListBackupsResponse +from google.cloud.alloydb_v1beta.types.service import ListClustersRequest +from google.cloud.alloydb_v1beta.types.service import ListClustersResponse +from google.cloud.alloydb_v1beta.types.service import ListInstancesRequest +from google.cloud.alloydb_v1beta.types.service import ListInstancesResponse +from google.cloud.alloydb_v1beta.types.service import ListSupportedDatabaseFlagsRequest +from google.cloud.alloydb_v1beta.types.service import ListSupportedDatabaseFlagsResponse +from google.cloud.alloydb_v1beta.types.service import ListUsersRequest +from google.cloud.alloydb_v1beta.types.service import ListUsersResponse +from google.cloud.alloydb_v1beta.types.service import OperationMetadata +from google.cloud.alloydb_v1beta.types.service import PromoteClusterRequest +from google.cloud.alloydb_v1beta.types.service import RestartInstanceRequest +from google.cloud.alloydb_v1beta.types.service import RestoreClusterRequest +from google.cloud.alloydb_v1beta.types.service import UpdateBackupRequest +from google.cloud.alloydb_v1beta.types.service import UpdateClusterRequest +from google.cloud.alloydb_v1beta.types.service import UpdateInstanceRequest +from google.cloud.alloydb_v1beta.types.service import UpdateUserRequest + +__all__ = ('AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ConnectionInfo', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetConnectionInfoRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/py.typed b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/__init__.py new file mode 100644 index 000000000000..b5c8c1c1be54 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/__init__.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.alloydb_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.alloy_db_admin import AlloyDBAdminClient +from .services.alloy_db_admin import AlloyDBAdminAsyncClient + +from .types.resources import AutomatedBackupPolicy +from .types.resources import Backup +from .types.resources import BackupSource +from .types.resources import Cluster +from .types.resources import ConnectionInfo +from .types.resources import ContinuousBackupConfig +from .types.resources import ContinuousBackupInfo +from .types.resources import ContinuousBackupSource +from .types.resources import EncryptionConfig +from .types.resources import EncryptionInfo +from .types.resources import Instance +from .types.resources import MigrationSource +from .types.resources import SslConfig +from .types.resources import SupportedDatabaseFlag +from .types.resources import User +from .types.resources import UserPassword +from .types.resources import ClusterView +from .types.resources import DatabaseVersion +from .types.resources import InstanceView +from .types.service import BatchCreateInstancesMetadata +from .types.service import BatchCreateInstancesRequest +from .types.service import BatchCreateInstancesResponse +from .types.service import BatchCreateInstanceStatus +from .types.service import CreateBackupRequest +from .types.service import CreateClusterRequest +from .types.service import CreateInstanceRequest +from .types.service import CreateInstanceRequests +from .types.service import CreateSecondaryClusterRequest +from .types.service import CreateSecondaryInstanceRequest +from .types.service import CreateUserRequest +from .types.service import DeleteBackupRequest +from .types.service import DeleteClusterRequest +from .types.service import DeleteInstanceRequest +from .types.service import DeleteUserRequest +from .types.service import FailoverInstanceRequest +from .types.service import GenerateClientCertificateRequest +from .types.service import GenerateClientCertificateResponse +from .types.service import GetBackupRequest +from .types.service import GetClusterRequest +from .types.service import GetConnectionInfoRequest +from .types.service import GetInstanceRequest +from .types.service import GetUserRequest +from .types.service import InjectFaultRequest +from .types.service import ListBackupsRequest +from .types.service import ListBackupsResponse +from .types.service import ListClustersRequest +from .types.service import ListClustersResponse +from .types.service import ListInstancesRequest +from .types.service import ListInstancesResponse +from .types.service import ListSupportedDatabaseFlagsRequest +from .types.service import ListSupportedDatabaseFlagsResponse +from .types.service import ListUsersRequest +from .types.service import ListUsersResponse +from .types.service import OperationMetadata +from .types.service import PromoteClusterRequest +from .types.service import RestartInstanceRequest +from .types.service import RestoreClusterRequest +from .types.service import UpdateBackupRequest +from .types.service import UpdateClusterRequest +from .types.service import UpdateInstanceRequest +from .types.service import UpdateUserRequest + +__all__ = ( + 'AlloyDBAdminAsyncClient', +'AlloyDBAdminClient', +'AutomatedBackupPolicy', +'Backup', +'BackupSource', +'BatchCreateInstanceStatus', +'BatchCreateInstancesMetadata', +'BatchCreateInstancesRequest', +'BatchCreateInstancesResponse', +'Cluster', +'ClusterView', +'ConnectionInfo', +'ContinuousBackupConfig', +'ContinuousBackupInfo', +'ContinuousBackupSource', +'CreateBackupRequest', +'CreateClusterRequest', +'CreateInstanceRequest', +'CreateInstanceRequests', +'CreateSecondaryClusterRequest', +'CreateSecondaryInstanceRequest', +'CreateUserRequest', +'DatabaseVersion', +'DeleteBackupRequest', +'DeleteClusterRequest', +'DeleteInstanceRequest', +'DeleteUserRequest', +'EncryptionConfig', +'EncryptionInfo', +'FailoverInstanceRequest', +'GenerateClientCertificateRequest', +'GenerateClientCertificateResponse', +'GetBackupRequest', +'GetClusterRequest', +'GetConnectionInfoRequest', +'GetInstanceRequest', +'GetUserRequest', +'InjectFaultRequest', +'Instance', +'InstanceView', +'ListBackupsRequest', +'ListBackupsResponse', +'ListClustersRequest', +'ListClustersResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListSupportedDatabaseFlagsRequest', +'ListSupportedDatabaseFlagsResponse', +'ListUsersRequest', +'ListUsersResponse', +'MigrationSource', +'OperationMetadata', +'PromoteClusterRequest', +'RestartInstanceRequest', +'RestoreClusterRequest', +'SslConfig', +'SupportedDatabaseFlag', +'UpdateBackupRequest', +'UpdateClusterRequest', +'UpdateInstanceRequest', +'UpdateUserRequest', +'User', +'UserPassword', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..5b0f0bfb7ae0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_metadata.json @@ -0,0 +1,493 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.alloydb_v1beta", + "protoPackage": "google.cloud.alloydb.v1beta", + "schema": "1.0", + "services": { + "AlloyDBAdmin": { + "clients": { + "grpc": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlloyDBAdminAsyncClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "rest": { + "libraryClient": "AlloyDBAdminClient", + "rpcs": { + "BatchCreateInstances": { + "methods": [ + "batch_create_instances" + ] + }, + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateCluster": { + "methods": [ + "create_cluster" + ] + }, + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "CreateSecondaryCluster": { + "methods": [ + "create_secondary_cluster" + ] + }, + "CreateSecondaryInstance": { + "methods": [ + "create_secondary_instance" + ] + }, + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteCluster": { + "methods": [ + "delete_cluster" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "FailoverInstance": { + "methods": [ + "failover_instance" + ] + }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetCluster": { + "methods": [ + "get_cluster" + ] + }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "InjectFault": { + "methods": [ + "inject_fault" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListClusters": { + "methods": [ + "list_clusters" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListSupportedDatabaseFlags": { + "methods": [ + "list_supported_database_flags" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "PromoteCluster": { + "methods": [ + "promote_cluster" + ] + }, + "RestartInstance": { + "methods": [ + "restart_instance" + ] + }, + "RestoreCluster": { + "methods": [ + "restore_cluster" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateCluster": { + "methods": [ + "update_cluster" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/py.typed b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/py.typed new file mode 100644 index 000000000000..c71d0f20b482 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-alloydb package uses inline types. diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/__init__.py new file mode 100644 index 000000000000..364ae3da06ba --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AlloyDBAdminClient +from .async_client import AlloyDBAdminAsyncClient + +__all__ = ( + 'AlloyDBAdminClient', + 'AlloyDBAdminAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py new file mode 100644 index 000000000000..6334bbea0a52 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py @@ -0,0 +1,4279 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.alloydb_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.alloydb_v1beta.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .client import AlloyDBAdminClient + + +class AlloyDBAdminAsyncClient: + """Service describing handlers for resources""" + + _client: AlloyDBAdminClient + + DEFAULT_ENDPOINT = AlloyDBAdminClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AlloyDBAdminClient.DEFAULT_MTLS_ENDPOINT + + backup_path = staticmethod(AlloyDBAdminClient.backup_path) + parse_backup_path = staticmethod(AlloyDBAdminClient.parse_backup_path) + cluster_path = staticmethod(AlloyDBAdminClient.cluster_path) + parse_cluster_path = staticmethod(AlloyDBAdminClient.parse_cluster_path) + connection_info_path = staticmethod(AlloyDBAdminClient.connection_info_path) + parse_connection_info_path = staticmethod(AlloyDBAdminClient.parse_connection_info_path) + crypto_key_version_path = staticmethod(AlloyDBAdminClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod(AlloyDBAdminClient.parse_crypto_key_version_path) + instance_path = staticmethod(AlloyDBAdminClient.instance_path) + parse_instance_path = staticmethod(AlloyDBAdminClient.parse_instance_path) + network_path = staticmethod(AlloyDBAdminClient.network_path) + parse_network_path = staticmethod(AlloyDBAdminClient.parse_network_path) + supported_database_flag_path = staticmethod(AlloyDBAdminClient.supported_database_flag_path) + parse_supported_database_flag_path = staticmethod(AlloyDBAdminClient.parse_supported_database_flag_path) + user_path = staticmethod(AlloyDBAdminClient.user_path) + parse_user_path = staticmethod(AlloyDBAdminClient.parse_user_path) + common_billing_account_path = staticmethod(AlloyDBAdminClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AlloyDBAdminClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AlloyDBAdminClient.common_folder_path) + parse_common_folder_path = staticmethod(AlloyDBAdminClient.parse_common_folder_path) + common_organization_path = staticmethod(AlloyDBAdminClient.common_organization_path) + parse_common_organization_path = staticmethod(AlloyDBAdminClient.parse_common_organization_path) + common_project_path = staticmethod(AlloyDBAdminClient.common_project_path) + parse_common_project_path = staticmethod(AlloyDBAdminClient.parse_common_project_path) + common_location_path = staticmethod(AlloyDBAdminClient.common_location_path) + parse_common_location_path = staticmethod(AlloyDBAdminClient.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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_info.__func__(AlloyDBAdminAsyncClient, 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: + AlloyDBAdminAsyncClient: The constructed client. + """ + return AlloyDBAdminClient.from_service_account_file.__func__(AlloyDBAdminAsyncClient, 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 AlloyDBAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AlloyDBAdminClient).get_transport_class, type(AlloyDBAdminClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AlloyDBAdminTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, ~.AlloyDBAdminTransport]): 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 = AlloyDBAdminClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersAsyncPager: + r"""Lists Clusters 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 alloydb_v1beta + + async def sample_list_clusters(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.ListClustersRequest, dict]]): + The request object. Message for requesting list of + Clusters + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListClustersAsyncPager: + Message for response to listing + Clusters + 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 = service.ListClustersRequest(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_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_get_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.GetClusterRequest, dict]]): + The request object. Message for getting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1beta.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetClusterRequest(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_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1beta + + async def sample_create_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.CreateClusterRequest, dict]]): + The request object. Message for creating a Cluster + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1beta.types.Cluster`): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_update_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.UpdateClusterRequest, dict]]): + The request object. Message for updating a Cluster + cluster (:class:`google.cloud.alloydb_v1beta.types.Cluster`): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 = service.UpdateClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster, + 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(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_delete_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.DeleteClusterRequest, dict]]): + The request object. Message for deleting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 = service.DeleteClusterRequest(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_cluster, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_promote_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.PromoteClusterRequest, dict]]): + The request object. Message for promoting a Cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.PromoteClusterRequest(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.promote_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, 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"""Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_restore_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1beta.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.RestoreClusterRequest, dict]]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + request = service.RestoreClusterRequest(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.restore_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.CreateSecondaryClusterRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (:class:`google.cloud.alloydb_v1beta.types.Cluster`): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (:class:`str`): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 = service.CreateSecondaryClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_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_secondary_cluster, + 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesAsyncPager: + r"""Lists Instances 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 alloydb_v1beta + + async def sample_list_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances + parent (:class:`str`): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances + 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 = service.ListInstancesRequest(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_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_get_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.GetInstanceRequest, dict]]): + The request object. Message for getting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1beta.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetInstanceRequest(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_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1beta + + async def sample_create_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.CreateInstanceRequest, dict]]): + The request object. Message for creating a Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1beta.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1beta + + async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.CreateSecondaryInstanceRequest, dict]]): + The request object. Message for creating a Secondary + Instance + parent (:class:`str`): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.alloydb_v1beta.types.Instance`): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 = service.CreateSecondaryInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_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_secondary_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, 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"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1beta.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.BatchCreateInstancesRequest, dict]]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1beta.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_instances, + 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_update_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.UpdateInstanceRequest, dict]]): + The request object. Message for updating a Instance + instance (:class:`google.cloud.alloydb_v1beta.types.Instance`): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 = service.UpdateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance, + 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(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_delete_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.DeleteInstanceRequest, dict]]): + The request object. Message for deleting a Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 = service.DeleteInstanceRequest(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_instance, + 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_failover_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.FailoverInstanceRequest, dict]]): + The request object. Message for triggering failover on an + Instance + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.FailoverInstanceRequest(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.failover_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_inject_fault(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.InjectFaultRequest, dict]]): + The request object. Message for triggering fault + injection on an instance + fault_type (:class:`google.cloud.alloydb_v1beta.types.InjectFaultRequest.FaultType`): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 = service.InjectFaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_restart_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.RestartInstanceRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.RestartInstanceRequest(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.restart_instance, + 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1beta + + async def sample_list_backups(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1beta.types.ListBackupsRequest, dict]]): + The request object. Message for requesting list of + Backups + parent (:class:`str`): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListBackupsAsyncPager: + Message for response to listing + Backups + 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup(self, + request: Optional[Union[service.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]] = (), + ) -> resources.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 alloydb_v1beta + + async def sample_get_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1beta.types.GetBackupRequest, dict]]): + The request object. Message for getting a Backup + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1beta.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup(self, + request: Optional[Union[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1beta + + async def sample_create_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1beta.types.CreateBackupRequest, dict]]): + The request object. Message for creating a Backup + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (:class:`google.cloud.alloydb_v1beta.types.Backup`): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (:class:`str`): + Required. ID of the requesting + object. + + 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.alloydb_v1beta.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.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=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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1beta + + async def sample_update_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.UpdateBackupRequest, dict]]): + The request object. Message for updating a Backup + backup (:class:`google.cloud.alloydb_v1beta.types.Backup`): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1beta.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 = service.UpdateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_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(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1beta + + async def sample_delete_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1beta.types.DeleteBackupRequest, dict]]): + The request object. Message for deleting a Backup + name (:class:`str`): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 = service.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=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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsAsyncPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1beta + + async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest, dict]]): + The request object. Message for listing the information + about the supported Database flags. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager: + Message for response to listing + SupportedDatabaseFlags. + 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 = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSupportedDatabaseFlagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_client_certificate(self, + request: Optional[Union[service.GenerateClientCertificateRequest, 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]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.GenerateClientCertificateRequest, dict]]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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.alloydb_v1beta.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate 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([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 = service.GenerateClientCertificateRequest(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.generate_client_certificate, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_connection_info(self, + request: Optional[Union[service.GetConnectionInfoRequest, 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]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_get_connection_info(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.GetConnectionInfoRequest, dict]]): + The request object. Request message for + GetConnectionInfo. + parent (:class:`str`): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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.alloydb_v1beta.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetConnectionInfoRequest(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.get_connection_info, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersAsyncPager: + r"""Lists Users 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 alloydb_v1beta + + async def sample_list_users(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.ListUsersRequest, dict]]): + The request object. Message for requesting list of Users + parent (:class:`str`): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListUsersAsyncPager: + Message for response to listing Users + + 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 = service.ListUsersRequest(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_users, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_get_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.GetUserRequest, dict]]): + The request object. Message for getting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetUserRequest(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_user, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_create_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.CreateUserRequest, dict]]): + The request object. Message for creating a User + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`google.cloud.alloydb_v1beta.types.User`): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (:class:`str`): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 = service.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_update_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.UpdateUserRequest, dict]]): + The request object. Message for updating a User + user (:class:`google.cloud.alloydb_v1beta.types.User`): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 = service.UpdateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user, + 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(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_delete_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.DeleteUserRequest, dict]]): + The request object. Message for deleting a User + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DeleteUserRequest(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_user, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AlloyDBAdminAsyncClient": + 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__ = ( + "AlloyDBAdminAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py new file mode 100644 index 000000000000..ca8177328819 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py @@ -0,0 +1,4477 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.alloydb_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.alloydb_v1beta.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +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 AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AlloyDBAdminGrpcTransport +from .transports.grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .transports.rest import AlloyDBAdminRestTransport + + +class AlloyDBAdminClientMeta(type): + """Metaclass for the AlloyDBAdmin 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[AlloyDBAdminTransport]] + _transport_registry["grpc"] = AlloyDBAdminGrpcTransport + _transport_registry["grpc_asyncio"] = AlloyDBAdminGrpcAsyncIOTransport + _transport_registry["rest"] = AlloyDBAdminRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AlloyDBAdminTransport]: + """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 AlloyDBAdminClient(metaclass=AlloyDBAdminClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "alloydb.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: + AlloyDBAdminClient: 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: + AlloyDBAdminClient: 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) -> AlloyDBAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AlloyDBAdminTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def backup_path(project: str,location: str,backup: str,) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, 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.+?)/backups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path(project: str,location: str,cluster: str,) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str,str]: + """Parses a cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def connection_info_path(project: str,location: str,cluster: str,instance: str,) -> str: + """Returns a fully-qualified connection_info string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format(project=project, location=location, cluster=cluster, instance=instance, ) + + @staticmethod + def parse_connection_info_path(path: str) -> Dict[str,str]: + """Parses a connection_info path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?P.+?)/connectionInfo$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str,str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_path(project: str,location: str,cluster: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?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 supported_database_flag_path(project: str,location: str,flag: str,) -> str: + """Returns a fully-qualified supported_database_flag string.""" + return "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + + @staticmethod + def parse_supported_database_flag_path(path: str) -> Dict[str,str]: + """Parses a supported_database_flag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/flags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(project: str,location: str,cluster: str,user: str,) -> str: + """Returns a fully-qualified user string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/users/(?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, AlloyDBAdminTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the alloy db admin 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, AlloyDBAdminTransport]): 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, AlloyDBAdminTransport): + # transport is a AlloyDBAdminTransport 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_clusters(self, + request: Optional[Union[service.ListClustersRequest, 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.ListClustersPager: + r"""Lists Clusters 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 alloydb_v1beta + + def sample_list_clusters(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.ListClustersRequest, dict]): + The request object. Message for requesting list of + Clusters + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Cluster.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with the following + format: + + - projects/{project}/locations/- + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListClustersPager: + Message for response to listing + Clusters + 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 service.ListClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListClustersRequest): + request = service.ListClustersRequest(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_clusters] + + # 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.ListClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cluster(self, + request: Optional[Union[service.GetClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Cluster: + r"""Gets details of a single Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_get_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GetClusterRequest, dict]): + The request object. Message for getting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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.alloydb_v1beta.types.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetClusterRequest): + request = service.GetClusterRequest(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_cluster] + + # Certain 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_cluster(self, + request: Optional[Union[service.CreateClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 Cluster 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 alloydb_v1beta + + def sample_create_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.CreateClusterRequest, dict]): + The request object. Message for creating a Cluster + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. The resource being created + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``cluster_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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateClusterRequest): + request = service.CreateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_cluster(self, + request: Optional[Union[service.UpdateClusterRequest, dict]] = None, + *, + cluster: Optional[resources.Cluster] = 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_update_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.UpdateClusterRequest, dict]): + The request object. Message for updating a Cluster + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. The resource being updated + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cluster, 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 service.UpdateClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateClusterRequest): + request = service.UpdateClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cluster is not None: + request.cluster = cluster + 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_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("cluster.name", request.cluster.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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_cluster(self, + request: Optional[Union[service.DeleteClusterRequest, 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 Cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_delete_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.DeleteClusterRequest, dict]): + The request object. Message for deleting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field. + + 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 service.DeleteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteClusterRequest): + request = service.DeleteClusterRequest(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_cluster] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def promote_cluster(self, + request: Optional[Union[service.PromoteClusterRequest, 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"""Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_promote_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.PromoteClusterRequest, dict]): + The request object. Message for promoting a Cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + 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.cloud.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.PromoteClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.PromoteClusterRequest): + request = service.PromoteClusterRequest(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.promote_cluster] + + # Certain 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_cluster(self, + request: Optional[Union[service.RestoreClusterRequest, dict]] = 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 Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_restore_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1beta.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.RestoreClusterRequest, dict]): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.RestoreClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestoreClusterRequest): + request = service.RestoreClusterRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_cluster(self, + request: Optional[Union[service.CreateSecondaryClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + cluster: Optional[resources.Cluster] = None, + cluster_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 cluster of type SECONDARY in the given + location using the primary cluster as the source. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.CreateSecondaryClusterRequest, dict]): + The request object. + parent (str): + Required. The location of the new + cluster. For the required format, see + the comment on the Cluster.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. Configuration of the + requesting object (the secondary + cluster). + + This corresponds to the ``cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cluster_id (str): + Required. ID of the requesting object + (the secondary cluster). + + This corresponds to the ``cluster_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.alloydb_v1beta.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # Create or coerce a protobuf request object. + # Quick 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, cluster, cluster_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 service.CreateSecondaryClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryClusterRequest): + request = service.CreateSecondaryClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cluster is not None: + request.cluster = cluster + if cluster_id is not None: + request.cluster_id = cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_cluster] + + # 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, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_instances(self, + request: Optional[Union[service.ListInstancesRequest, 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.ListInstancesPager: + r"""Lists Instances 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 alloydb_v1beta + + def sample_list_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances + parent (str): + Required. The name of the parent resource. For the + required format, see the comment on the Instance.name + field. Additionally, you can perform an aggregated list + operation by specifying a value with one of the + following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListInstancesPager: + Message for response to listing + Instances + 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 service.ListInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListInstancesRequest): + request = service.ListInstancesRequest(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_instances] + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[service.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_get_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GetInstanceRequest, dict]): + The request object. Message for getting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.alloydb_v1beta.types.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetInstanceRequest): + request = service.GetInstanceRequest(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_instance] + + # Certain 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_instance(self, + request: Optional[Union[service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 Instance 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 alloydb_v1beta + + def sample_create_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.CreateInstanceRequest, dict]): + The request object. Message for creating a Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateInstanceRequest): + request = service.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_secondary_instance(self, + request: Optional[Union[service.CreateSecondaryInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[resources.Instance] = None, + instance_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 SECONDARY Instance 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 alloydb_v1beta + + def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.CreateSecondaryInstanceRequest, dict]): + The request object. Message for creating a Secondary + Instance + parent (str): + Required. The name of the parent + resource. For the required format, see + the comment on the Instance.name field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being created + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``instance_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.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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, instance, instance_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 service.CreateSecondaryInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecondaryInstanceRequest): + request = service.CreateSecondaryInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secondary_instance] + + # 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def batch_create_instances(self, + request: Optional[Union[service.BatchCreateInstancesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_batch_create_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1beta.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.BatchCreateInstancesRequest, dict]): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.alloydb_v1beta.types.BatchCreateInstancesResponse` + Message for creating batches of instances in a cluster. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.BatchCreateInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.BatchCreateInstancesRequest): + request = service.BatchCreateInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_instances] + + # 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, + service.BatchCreateInstancesResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_instance(self, + request: Optional[Union[service.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[resources.Instance] = 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_update_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.UpdateInstanceRequest, dict]): + The request object. Message for updating a Instance + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being updated + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([instance, 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 service.UpdateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateInstanceRequest): + request = service.UpdateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("instance.name", request.instance.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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_instance(self, + request: Optional[Union[service.DeleteInstanceRequest, 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 Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_delete_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.DeleteInstanceRequest, dict]): + The request object. Message for deleting a Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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 service.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteInstanceRequest): + request = service.DeleteInstanceRequest(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_instance] + + # Certain 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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def failover_instance(self, + request: Optional[Union[service.FailoverInstanceRequest, 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"""Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_failover_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.FailoverInstanceRequest, dict]): + The request object. Message for triggering failover on an + Instance + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.FailoverInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.FailoverInstanceRequest): + request = service.FailoverInstanceRequest(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.failover_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def inject_fault(self, + request: Optional[Union[service.InjectFaultRequest, dict]] = None, + *, + fault_type: Optional[service.InjectFaultRequest.FaultType] = 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"""Injects fault in an instance. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_inject_fault(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.InjectFaultRequest, dict]): + The request object. Message for triggering fault + injection on an instance + fault_type (google.cloud.alloydb_v1beta.types.InjectFaultRequest.FaultType): + Required. The type of fault to be + injected in an instance. + + This corresponds to the ``fault_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fault_type, 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 service.InjectFaultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.InjectFaultRequest): + request = service.InjectFaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fault_type is not None: + request.fault_type = fault_type + 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.inject_fault] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def restart_instance(self, + request: Optional[Union[service.RestartInstanceRequest, 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"""Restart an Instance in a cluster. + Imperative only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_restart_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.RestartInstanceRequest, dict]): + The request object. + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Instance.name field. + + 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.cloud.alloydb_v1beta.types.Instance` An Instance is a computing unit that an end customer can connect to. + It's the main unit of computing resources in AlloyDB. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.RestartInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestartInstanceRequest): + request = service.RestartInstanceRequest(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.restart_instance] + + # Certain 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, + resources.Instance, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups(self, + request: Optional[Union[service.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 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 alloydb_v1beta + + def sample_list_backups(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1beta.types.ListBackupsRequest, dict]): + The request object. Message for requesting list of + Backups + parent (str): + Required. Parent value for + ListBackupsRequest + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListBackupsPager: + Message for response to listing + Backups + 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 service.ListBackupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListBackupsRequest): + request = service.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[service.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]] = (), + ) -> resources.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 alloydb_v1beta + + def sample_get_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GetBackupRequest, dict]): + The request object. Message for getting a Backup + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1beta.types.Backup: + Message describing Backup object + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetBackupRequest): + request = service.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[service.CreateBackupRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup: Optional[resources.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 alloydb_v1beta + + def sample_create_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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.alloydb_v1beta.types.CreateBackupRequest, dict]): + The request object. Message for creating a Backup + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup (google.cloud.alloydb_v1beta.types.Backup): + Required. The resource being created + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_id (str): + Required. ID of the requesting + object. + + 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.alloydb_v1beta.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.CreateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateBackupRequest): + request = service.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_backup(self, + request: Optional[Union[service.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[resources.Backup] = 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 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 alloydb_v1beta + + def sample_update_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.UpdateBackupRequest, dict]): + The request object. Message for updating a Backup + backup (google.cloud.alloydb_v1beta.types.Backup): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.alloydb_v1beta.types.Backup` + Message describing Backup object + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([backup, 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 service.UpdateBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateBackupRequest): + request = service.UpdateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + 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_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("backup.name", request.backup.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, + resources.Backup, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup(self, + request: Optional[Union[service.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 alloydb_v1beta + + def sample_delete_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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.alloydb_v1beta.types.DeleteBackupRequest, dict]): + The request object. Message for deleting a Backup + name (str): + Required. Name of the resource. For + the required format, see the comment on + the Backup.name field. + + 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 service.DeleteBackupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteBackupRequest): + request = service.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=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_supported_database_flags(self, + request: Optional[Union[service.ListSupportedDatabaseFlagsRequest, 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.ListSupportedDatabaseFlagsPager: + r"""Lists SupportedDatabaseFlags for 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 alloydb_v1beta + + def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest, dict]): + The request object. Message for listing the information + about the supported Database flags. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note + that we do not yet support region-specific flags. + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager: + Message for response to listing + SupportedDatabaseFlags. + 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 service.ListSupportedDatabaseFlagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSupportedDatabaseFlagsRequest): + request = service.ListSupportedDatabaseFlagsRequest(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_supported_database_flags] + + # 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.ListSupportedDatabaseFlagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_client_certificate(self, + request: Optional[Union[service.GenerateClientCertificateRequest, 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]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GenerateClientCertificateRequest, dict]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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.alloydb_v1beta.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate 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([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 service.GenerateClientCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateClientCertificateRequest): + request = service.GenerateClientCertificateRequest(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.generate_client_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_connection_info(self, + request: Optional[Union[service.GetConnectionInfoRequest, 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]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_get_connection_info(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GetConnectionInfoRequest, dict]): + The request object. Request message for + GetConnectionInfo. + parent (str): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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.alloydb_v1beta.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetConnectionInfoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetConnectionInfoRequest): + request = service.GetConnectionInfoRequest(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.get_connection_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 = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_users(self, + request: Optional[Union[service.ListUsersRequest, 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.ListUsersPager: + r"""Lists Users 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 alloydb_v1beta + + def sample_list_users(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.ListUsersRequest, dict]): + The request object. Message for requesting list of Users + parent (str): + Required. Parent value for + ListUsersRequest + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListUsersPager: + Message for response to listing Users + + 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 service.ListUsersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListUsersRequest): + request = service.ListUsersRequest(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_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_user(self, + request: Optional[Union[service.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Gets details of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_get_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.GetUserRequest, dict]): + The request object. Message for getting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + 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.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetUserRequest): + request = service.GetUserRequest(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_user] + + # Certain 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_user(self, + request: Optional[Union[service.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[resources.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Creates a new User in a given project, location, and + cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_create_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.CreateUserRequest, dict]): + The request object. Message for creating a User + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (google.cloud.alloydb_v1beta.types.User): + Required. The resource being created + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (str): + Required. ID of the requesting + object. + + This corresponds to the ``user_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.cloud.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick 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, user, user_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 service.CreateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateUserRequest): + request = service.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user(self, + request: Optional[Union[service.UpdateUserRequest, dict]] = None, + *, + user: Optional[resources.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.User: + r"""Updates the parameters of a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_update_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.UpdateUserRequest, dict]): + The request object. Message for updating a User + user (google.cloud.alloydb_v1beta.types.User): + Required. The resource being updated + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1beta.types.User: + Message describing User object. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([user, 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 service.UpdateUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateUserRequest): + request = service.UpdateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + 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_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_user(self, + request: Optional[Union[service.DeleteUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a single User. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_delete_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.DeleteUserRequest, dict]): + The request object. Message for deleting a User + name (str): + Required. The name of the resource. + For the required format, see the comment + on the User.name field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteUserRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteUserRequest): + request = service.DeleteUserRequest(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_user] + + # Certain 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 __enter__(self) -> "AlloyDBAdminClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AlloyDBAdminClient", +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py new file mode 100644 index 000000000000..8deed6310792 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py @@ -0,0 +1,624 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service + + +class ListClustersPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListClustersResponse` + 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[..., service.ListClustersResponse], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1beta.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListClustersResponse]: + 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[resources.Cluster]: + for page in self.pages: + yield from page.clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClustersAsyncPager: + """A pager for iterating through ``list_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClusters`` requests and continue to iterate + through the ``clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListClustersResponse` + 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[service.ListClustersResponse]], + request: service.ListClustersRequest, + response: service.ListClustersResponse, + *, + 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.alloydb_v1beta.types.ListClustersRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListClustersResponse): + 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 = service.ListClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListClustersResponse]: + 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[resources.Cluster]: + async def async_generator(): + async for page in self.pages: + for response in page.clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListInstancesResponse` + 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[..., service.ListInstancesResponse], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1beta.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListInstancesResponse]: + 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[resources.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListInstancesResponse` + 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[service.ListInstancesResponse]], + request: service.ListInstancesRequest, + response: service.ListInstancesResponse, + *, + 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.alloydb_v1beta.types.ListInstancesRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListInstancesResponse): + 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 = service.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListInstancesResponse]: + 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[resources.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + 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.alloydb_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.alloydb_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[..., service.ListBackupsResponse], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.ListBackupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.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[resources.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.alloydb_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.alloydb_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[service.ListBackupsResponse]], + request: service.ListBackupsRequest, + response: service.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.alloydb_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.alloydb_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 = service.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[service.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[resources.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) + + +class ListSupportedDatabaseFlagsPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse` + 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[..., service.ListSupportedDatabaseFlagsResponse], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + for page in self.pages: + yield from page.supported_database_flags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSupportedDatabaseFlagsAsyncPager: + """A pager for iterating through ``list_supported_database_flags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``supported_database_flags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSupportedDatabaseFlags`` requests and continue to iterate + through the ``supported_database_flags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse` + 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[service.ListSupportedDatabaseFlagsResponse]], + request: service.ListSupportedDatabaseFlagsRequest, + response: service.ListSupportedDatabaseFlagsResponse, + *, + 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.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsResponse): + 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 = service.ListSupportedDatabaseFlagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListSupportedDatabaseFlagsResponse]: + 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[resources.SupportedDatabaseFlag]: + async def async_generator(): + async for page in self.pages: + for response in page.supported_database_flags: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListUsersResponse` + 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[..., service.ListUsersResponse], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1beta.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListUsersResponse]: + 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[resources.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListUsersResponse` + 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[service.ListUsersResponse]], + request: service.ListUsersRequest, + response: service.ListUsersResponse, + *, + 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.alloydb_v1beta.types.ListUsersRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListUsersResponse): + 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 = service.ListUsersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListUsersResponse]: + 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[resources.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/__init__.py new file mode 100644 index 000000000000..9d544d8e4648 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AlloyDBAdminTransport +from .grpc import AlloyDBAdminGrpcTransport +from .grpc_asyncio import AlloyDBAdminGrpcAsyncIOTransport +from .rest import AlloyDBAdminRestTransport +from .rest import AlloyDBAdminRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AlloyDBAdminTransport]] +_transport_registry['grpc'] = AlloyDBAdminGrpcTransport +_transport_registry['grpc_asyncio'] = AlloyDBAdminGrpcAsyncIOTransport +_transport_registry['rest'] = AlloyDBAdminRestTransport + +__all__ = ( + 'AlloyDBAdminTransport', + 'AlloyDBAdminGrpcTransport', + 'AlloyDBAdminGrpcAsyncIOTransport', + 'AlloyDBAdminRestTransport', + 'AlloyDBAdminRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py new file mode 100644 index 000000000000..346d64dc8860 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py @@ -0,0 +1,698 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.alloydb_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.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AlloyDBAdminTransport(abc.ABC): + """Abstract transport class for AlloyDBAdmin.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'alloydb.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_clusters: gapic_v1.method.wrap_method( + self.list_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_cluster: gapic_v1.method.wrap_method( + self.get_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_cluster: gapic_v1.method.wrap_method( + self.create_cluster, + default_timeout=None, + client_info=client_info, + ), + self.update_cluster: gapic_v1.method.wrap_method( + self.update_cluster, + default_timeout=None, + client_info=client_info, + ), + self.delete_cluster: gapic_v1.method.wrap_method( + self.delete_cluster, + default_timeout=None, + client_info=client_info, + ), + self.promote_cluster: gapic_v1.method.wrap_method( + self.promote_cluster, + default_timeout=None, + client_info=client_info, + ), + self.restore_cluster: gapic_v1.method.wrap_method( + self.restore_cluster, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_cluster: gapic_v1.method.wrap_method( + self.create_secondary_cluster, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_secondary_instance: gapic_v1.method.wrap_method( + self.create_secondary_instance, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_instances: gapic_v1.method.wrap_method( + self.batch_create_instances, + default_timeout=None, + client_info=client_info, + ), + self.update_instance: gapic_v1.method.wrap_method( + self.update_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.failover_instance: gapic_v1.method.wrap_method( + self.failover_instance, + default_timeout=None, + client_info=client_info, + ), + self.inject_fault: gapic_v1.method.wrap_method( + self.inject_fault, + default_timeout=None, + client_info=client_info, + ), + self.restart_instance: gapic_v1.method.wrap_method( + self.restart_instance, + default_timeout=None, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup: gapic_v1.method.wrap_method( + self.create_backup, + default_timeout=None, + client_info=client_info, + ), + self.update_backup: gapic_v1.method.wrap_method( + self.update_backup, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.list_supported_database_flags: gapic_v1.method.wrap_method( + self.list_supported_database_flags, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_client_certificate: gapic_v1.method.wrap_method( + self.generate_client_certificate, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_connection_info: gapic_v1.method.wrap_method( + self.get_connection_info, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + 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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Union[ + service.ListClustersResponse, + Awaitable[service.ListClustersResponse] + ]]: + raise NotImplementedError() + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Union[ + resources.Cluster, + Awaitable[resources.Cluster] + ]]: + raise NotImplementedError() + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Union[ + service.ListInstancesResponse, + Awaitable[service.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Union[ + resources.Instance, + Awaitable[resources.Instance] + ]]: + raise NotImplementedError() + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Union[ + service.ListBackupsResponse, + Awaitable[service.ListBackupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Union[ + resources.Backup, + Awaitable[resources.Backup] + ]]: + raise NotImplementedError() + + @property + def create_backup(self) -> Callable[ + [service.CreateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_backup(self) -> Callable[ + [service.DeleteBackupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Union[ + service.ListSupportedDatabaseFlagsResponse, + Awaitable[service.ListSupportedDatabaseFlagsResponse] + ]]: + raise NotImplementedError() + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + Union[ + service.GenerateClientCertificateResponse, + Awaitable[service.GenerateClientCertificateResponse] + ]]: + raise NotImplementedError() + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + Union[ + resources.ConnectionInfo, + Awaitable[resources.ConnectionInfo] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Union[ + service.ListUsersResponse, + Awaitable[service.ListUsersResponse] + ]]: + raise NotImplementedError() + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Union[ + resources.User, + Awaitable[resources.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AlloyDBAdminTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py new file mode 100644 index 000000000000..d3a1542dc6da --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py @@ -0,0 +1,1210 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import 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.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO + + +class AlloyDBAdminGrpcTransport(AlloyDBAdminTransport): + """gRPC backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + ~.ListClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + ~.Cluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + ~.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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + ~.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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + ~.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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + ~.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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + ~.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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + ~.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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + operations_pb2.Operation]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + ~.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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + ~.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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1beta.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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.alloydb.v1beta.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1beta.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + operations_pb2.Operation]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + ~.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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1beta.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + ~.ListSupportedDatabaseFlagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + ~.GenerateClientCertificateResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_client_certificate' not in self._stubs: + self._stubs['generate_client_certificate'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GenerateClientCertificate', + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs['generate_client_certificate'] + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + resources.ConnectionInfo]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + ~.ConnectionInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connection_info' not in self._stubs: + self._stubs['get_connection_info'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetConnectionInfo', + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs['get_connection_info'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AlloyDBAdminGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py new file mode 100644 index 000000000000..758f5d7585a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py @@ -0,0 +1,1209 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.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.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 # type: ignore +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 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AlloyDBAdminTransport, DEFAULT_CLIENT_INFO +from .grpc import AlloyDBAdminGrpcTransport + + +class AlloyDBAdminGrpcAsyncIOTransport(AlloyDBAdminTransport): + """gRPC AsyncIO backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'alloydb.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 = 'alloydb.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + Awaitable[service.ListClustersResponse]]: + r"""Return a callable for the list clusters method over gRPC. + + Lists Clusters in a given project and location. + + Returns: + Callable[[~.ListClustersRequest], + Awaitable[~.ListClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_clusters' not in self._stubs: + self._stubs['list_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListClusters', + request_serializer=service.ListClustersRequest.serialize, + response_deserializer=service.ListClustersResponse.deserialize, + ) + return self._stubs['list_clusters'] + + @property + def get_cluster(self) -> Callable[ + [service.GetClusterRequest], + Awaitable[resources.Cluster]]: + r"""Return a callable for the get cluster method over gRPC. + + Gets details of a single Cluster. + + Returns: + Callable[[~.GetClusterRequest], + Awaitable[~.Cluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_cluster' not in self._stubs: + self._stubs['get_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetCluster', + request_serializer=service.GetClusterRequest.serialize, + response_deserializer=resources.Cluster.deserialize, + ) + return self._stubs['get_cluster'] + + @property + def create_cluster(self) -> Callable[ + [service.CreateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create cluster method over gRPC. + + Creates a new Cluster in a given project and + location. + + Returns: + Callable[[~.CreateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['create_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateCluster', + request_serializer=service.CreateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_cluster'] + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update cluster method over gRPC. + + Updates the parameters of a single Cluster. + + Returns: + Callable[[~.UpdateClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['update_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateCluster', + request_serializer=service.UpdateClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_cluster'] + + @property + def delete_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete cluster method over gRPC. + + Deletes a single Cluster. + + Returns: + Callable[[~.DeleteClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteCluster', + request_serializer=service.DeleteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_cluster'] + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the promote cluster method over gRPC. + + Promotes a SECONDARY cluster. This turns down + replication from the PRIMARY cluster and promotes a + secondary cluster into its own standalone cluster. + Imperative only. + + Returns: + Callable[[~.PromoteClusterRequest], + 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 'promote_cluster' not in self._stubs: + self._stubs['promote_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/PromoteCluster', + request_serializer=service.PromoteClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['promote_cluster'] + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore cluster method over gRPC. + + Creates a new Cluster in a given project and + location, with a volume restored from the provided + source, either a backup ID or a point-in-time and a + source cluster. + + Returns: + Callable[[~.RestoreClusterRequest], + 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_cluster' not in self._stubs: + self._stubs['restore_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/RestoreCluster', + request_serializer=service.RestoreClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_cluster'] + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary cluster method over gRPC. + + Creates a cluster of type SECONDARY in the given + location using the primary cluster as the source. + + Returns: + Callable[[~.CreateSecondaryClusterRequest], + 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_secondary_cluster' not in self._stubs: + self._stubs['create_secondary_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateSecondaryCluster', + request_serializer=service.CreateSecondaryClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_cluster'] + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + Awaitable[service.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListInstances', + request_serializer=service.ListInstancesRequest.serialize, + response_deserializer=service.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + Awaitable[resources.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetInstance', + request_serializer=service.GetInstanceRequest.serialize, + response_deserializer=resources.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create instance method over gRPC. + + Creates a new Instance in a given project and + location. + + Returns: + Callable[[~.CreateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateInstance', + request_serializer=service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create secondary instance method over gRPC. + + Creates a new SECONDARY Instance in a given project + and location. + + Returns: + Callable[[~.CreateSecondaryInstanceRequest], + 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_secondary_instance' not in self._stubs: + self._stubs['create_secondary_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateSecondaryInstance', + request_serializer=service.CreateSecondaryInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_secondary_instance'] + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch create instances method over gRPC. + + Creates new instances under the given project, + location and cluster. There can be only one primary + instance in a cluster. If the primary instance exists in + the cluster as well as this request, then API will throw + an error. + The primary instance should exist before any read pool + instance is created. If the primary instance is a part + of the request payload, then the API will take care of + creating instances in the correct order. This method is + here to support Google-internal use cases, and is not + meant for external customers to consume. Please do not + start relying on it; its behavior is subject to change + without notice. + + Returns: + Callable[[~.BatchCreateInstancesRequest], + 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 'batch_create_instances' not in self._stubs: + self._stubs['batch_create_instances'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/BatchCreateInstances', + request_serializer=service.BatchCreateInstancesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_instances'] + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['update_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateInstance', + request_serializer=service.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_instance'] + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + 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_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteInstance', + request_serializer=service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the failover instance method over gRPC. + + Forces a Failover for a highly available instance. + Failover promotes the HA standby instance as the new + primary. Imperative only. + + Returns: + Callable[[~.FailoverInstanceRequest], + 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 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/FailoverInstance', + request_serializer=service.FailoverInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['failover_instance'] + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the inject fault method over gRPC. + + Injects fault in an instance. + Imperative only. + + Returns: + Callable[[~.InjectFaultRequest], + 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 'inject_fault' not in self._stubs: + self._stubs['inject_fault'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/InjectFault', + request_serializer=service.InjectFaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['inject_fault'] + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restart instance method over gRPC. + + Restart an Instance in a cluster. + Imperative only. + + Returns: + Callable[[~.RestartInstanceRequest], + 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 'restart_instance' not in self._stubs: + self._stubs['restart_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/RestartInstance', + request_serializer=service.RestartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_instance'] + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + Awaitable[service.ListBackupsResponse]]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + 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.alloydb.v1beta.AlloyDBAdmin/ListBackups', + request_serializer=service.ListBackupsRequest.serialize, + response_deserializer=service.ListBackupsResponse.deserialize, + ) + return self._stubs['list_backups'] + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + Awaitable[resources.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.alloydb.v1beta.AlloyDBAdmin/GetBackup', + request_serializer=service.GetBackupRequest.serialize, + response_deserializer=resources.Backup.deserialize, + ) + return self._stubs['get_backup'] + + @property + def create_backup(self) -> Callable[ + [service.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.alloydb.v1beta.AlloyDBAdmin/CreateBackup', + request_serializer=service.CreateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_backup'] + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update backup method over gRPC. + + Updates the parameters of a single Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + 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_backup' not in self._stubs: + self._stubs['update_backup'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateBackup', + request_serializer=service.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_backup'] + + @property + def delete_backup(self) -> Callable[ + [service.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.alloydb.v1beta.AlloyDBAdmin/DeleteBackup', + request_serializer=service.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_backup'] + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + Awaitable[service.ListSupportedDatabaseFlagsResponse]]: + r"""Return a callable for the list supported database flags method over gRPC. + + Lists SupportedDatabaseFlags for a given project and + location. + + Returns: + Callable[[~.ListSupportedDatabaseFlagsRequest], + Awaitable[~.ListSupportedDatabaseFlagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_supported_database_flags' not in self._stubs: + self._stubs['list_supported_database_flags'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListSupportedDatabaseFlags', + request_serializer=service.ListSupportedDatabaseFlagsRequest.serialize, + response_deserializer=service.ListSupportedDatabaseFlagsResponse.deserialize, + ) + return self._stubs['list_supported_database_flags'] + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + Awaitable[service.GenerateClientCertificateResponse]]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + Awaitable[~.GenerateClientCertificateResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_client_certificate' not in self._stubs: + self._stubs['generate_client_certificate'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GenerateClientCertificate', + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs['generate_client_certificate'] + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + Awaitable[resources.ConnectionInfo]]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + Awaitable[~.ConnectionInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connection_info' not in self._stubs: + self._stubs['get_connection_info'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetConnectionInfo', + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs['get_connection_info'] + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + Awaitable[service.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists Users in a given project and location. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_users' not in self._stubs: + self._stubs['list_users'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListUsers', + request_serializer=service.ListUsersRequest.serialize, + response_deserializer=service.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the get user method over gRPC. + + Gets details of a single User. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['get_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/GetUser', + request_serializer=service.GetUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a new User in a given project, location, and + cluster. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['create_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/CreateUser', + request_serializer=service.CreateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + Awaitable[resources.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates the parameters of a single User. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user' not in self._stubs: + self._stubs['update_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/UpdateUser', + request_serializer=service.UpdateUserRequest.serialize, + response_deserializer=resources.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a single User. + + Returns: + Callable[[~.DeleteUserRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_user' not in self._stubs: + self._stubs['delete_user'] = self.grpc_channel.unary_unary( + '/google.cloud.alloydb.v1beta.AlloyDBAdmin/DeleteUser', + request_serializer=service.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'AlloyDBAdminGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py new file mode 100644 index 000000000000..262e8c323db7 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py @@ -0,0 +1,4327 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.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 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.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import AlloyDBAdminTransport, 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 AlloyDBAdminRestInterceptor: + """Interceptor for AlloyDBAdmin. + + 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 AlloyDBAdminRestTransport. + + .. code-block:: python + class MyCustomAlloyDBAdminInterceptor(AlloyDBAdminRestInterceptor): + def pre_batch_create_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_instances(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_secondary_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_secondary_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_failover_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_failover_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_client_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_client_certificate(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_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_connection_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connection_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_inject_fault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_inject_fault(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_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_supported_database_flags(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_supported_database_flags(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_promote_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_promote_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restart_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restart_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AlloyDBAdminRestTransport(interceptor=MyCustomAlloyDBAdminInterceptor()) + client = AlloyDBAdminClient(transport=transport) + + + """ + def pre_batch_create_instances(self, request: service.BatchCreateInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.BatchCreateInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_batch_create_instances(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_create_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_backup(self, request: service.CreateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_cluster(self, request: service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_instance(self, request: service.CreateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_cluster(self, request: service.CreateSecondaryClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_secondary_instance(self, request: service.CreateSecondaryInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateSecondaryInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_secondary_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_secondary_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_create_user(self, request: service.CreateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_create_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for create_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_backup(self, request: service.DeleteBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_cluster(self, request: service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_instance(self, request: service.DeleteInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_delete_user(self, request: service.DeleteUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def pre_failover_instance(self, request: service.FailoverInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.FailoverInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for failover_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for failover_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_generate_client_certificate(self, request: service.GenerateClientCertificateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateClientCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_generate_client_certificate(self, response: service.GenerateClientCertificateResponse) -> service.GenerateClientCertificateResponse: + """Post-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_backup(self, request: service.GetBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_get_backup(self, response: resources.Backup) -> resources.Backup: + """Post-rpc interceptor for get_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_cluster(self, request: service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: + """Post-rpc interceptor for get_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_connection_info(self, request: service.GetConnectionInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetConnectionInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_connection_info(self, response: resources.ConnectionInfo) -> resources.ConnectionInfo: + """Post-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_instance(self, response: resources.Instance) -> resources.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_user(self, request: service.GetUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for get_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_inject_fault(self, request: service.InjectFaultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.InjectFaultRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for inject_fault + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_inject_fault(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for inject_fault + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_backups(self, request: service.ListBackupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.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 AlloyDBAdmin server. + """ + return request, metadata + + def post_list_backups(self, response: service.ListBackupsResponse) -> service.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_clusters(self, request: service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_clusters(self, response: service.ListClustersResponse) -> service.ListClustersResponse: + """Post-rpc interceptor for list_clusters + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_instances(self, request: service.ListInstancesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_instances(self, response: service.ListInstancesResponse) -> service.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_supported_database_flags(self, request: service.ListSupportedDatabaseFlagsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListSupportedDatabaseFlagsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_supported_database_flags(self, response: service.ListSupportedDatabaseFlagsResponse) -> service.ListSupportedDatabaseFlagsResponse: + """Post-rpc interceptor for list_supported_database_flags + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_users(self, request: service.ListUsersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListUsersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_users(self, response: service.ListUsersResponse) -> service.ListUsersResponse: + """Post-rpc interceptor for list_users + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_promote_cluster(self, request: service.PromoteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.PromoteClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_promote_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for promote_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restart_instance(self, request: service.RestartInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestartInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restart_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restart_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restart_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_restore_cluster(self, request: service.RestoreClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestoreClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_restore_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_backup(self, request: service.UpdateBackupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateBackupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_backup(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_cluster(self, request: service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_cluster + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_instance(self, request: service.UpdateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_update_user(self, request: service.UpdateUserRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateUserRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_update_user(self, response: resources.User) -> resources.User: + """Post-rpc interceptor for update_user + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin 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 AlloyDBAdmin server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AlloyDBAdminRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AlloyDBAdminRestInterceptor + + +class AlloyDBAdminRestTransport(AlloyDBAdminTransport): + """REST backend transport for AlloyDBAdmin. + + Service describing handlers for resources + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'alloydb.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[AlloyDBAdminRestInterceptor] = 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 AlloyDBAdminRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + }, + ], + '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 _BatchCreateInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("BatchCreateInstances") + + __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: service.BatchCreateInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch create instances method over HTTP. + + Args: + request (~.service.BatchCreateInstancesRequest): + The request object. Message for creating a batch of + instances under the specified cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:batchCreate', + 'body': 'requests', + }, + ] + request, metadata = self._interceptor.pre_batch_create_instances(request, metadata) + pb_request = service.BatchCreateInstancesRequest.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_batch_create_instances(resp) + return resp + + class _CreateBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.CreateBackupRequest): + The request object. Message for creating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/backups', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_create_backup(request, metadata) + pb_request = service.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 _CreateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create cluster method over HTTP. + + Args: + request (~.service.CreateClusterRequest): + The request object. Message for creating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_cluster(request, metadata) + pb_request = service.CreateClusterRequest.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_cluster(resp) + return resp + + class _CreateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.service.CreateInstanceRequest): + The request object. Message for creating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_instance(request, metadata) + pb_request = service.CreateInstanceRequest.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_instance(resp) + return resp + + class _CreateSecondaryCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary cluster method over HTTP. + + Args: + request (~.service.CreateSecondaryClusterRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/*}/clusters:createsecondary', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_cluster(request, metadata) + pb_request = service.CreateSecondaryClusterRequest.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_secondary_cluster(resp) + return resp + + class _CreateSecondaryInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateSecondaryInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateSecondaryInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create secondary instance method over HTTP. + + Args: + request (~.service.CreateSecondaryInstanceRequest): + The request object. Message for creating a Secondary + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}/instances:createsecondary', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_secondary_instance(request, metadata) + pb_request = service.CreateSecondaryInstanceRequest.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_secondary_instance(resp) + return resp + + class _CreateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("CreateUser") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the create user method over HTTP. + + Args: + request (~.service.CreateUserRequest): + The request object. Message for creating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/clusters/*}/users', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_create_user(request, metadata) + pb_request = service.CreateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_user(resp) + return resp + + class _DeleteBackup(AlloyDBAdminRestStub): + 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: service.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 (~.service.DeleteBackupRequest): + The request object. Message for deleting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + pb_request = service.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 _DeleteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteCluster") + + __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: service.DeleteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete cluster method over HTTP. + + Args: + request (~.service.DeleteClusterRequest): + The request object. Message for deleting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_cluster(request, metadata) + pb_request = service.DeleteClusterRequest.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_cluster(resp) + return resp + + class _DeleteInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteInstance") + + __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: service.DeleteInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.service.DeleteInstanceRequest): + The request object. Message for deleting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + pb_request = service.DeleteInstanceRequest.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_instance(resp) + return resp + + class _DeleteUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("DeleteUser") + + __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: service.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.service.DeleteUserRequest): + The request object. Message for deleting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user(request, metadata) + pb_request = service.DeleteUserRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FailoverInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("FailoverInstance") + + __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: service.FailoverInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the failover instance method over HTTP. + + Args: + request (~.service.FailoverInstanceRequest): + The request object. Message for triggering failover on an + Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:failover', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_failover_instance(request, metadata) + pb_request = service.FailoverInstanceRequest.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_failover_instance(resp) + return resp + + class _GenerateClientCertificate(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GenerateClientCertificate") + + __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: service.GenerateClientCertificateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.GenerateClientCertificateResponse: + r"""Call the generate client + certificate method over HTTP. + + Args: + request (~.service.GenerateClientCertificateRequest): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_client_certificate(request, metadata) + pb_request = service.GenerateClientCertificateRequest.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 = service.GenerateClientCertificateResponse() + pb_resp = service.GenerateClientCertificateResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_client_certificate(resp) + return resp + + class _GetBackup(AlloyDBAdminRestStub): + 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: service.GetBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.service.GetBackupRequest): + The request object. Message for getting a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Backup: + Message describing Backup object + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/backups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_backup(request, metadata) + pb_request = service.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 = resources.Backup() + pb_resp = resources.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_backup(resp) + return resp + + class _GetCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetCluster") + + __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: service.GetClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Cluster: + r"""Call the get cluster method over HTTP. + + Args: + request (~.service.GetClusterRequest): + The request object. Message for getting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Cluster: + A cluster is a collection of regional + AlloyDB resources. It can include a + primary instance and one or more read + pool instances. All cluster resources + share a storage layer, which scales as + needed. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/clusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_cluster(request, metadata) + pb_request = service.GetClusterRequest.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 = resources.Cluster() + pb_resp = resources.Cluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_cluster(resp) + return resp + + class _GetConnectionInfo(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetConnectionInfo") + + __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: service.GetConnectionInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConnectionInfo: + r"""Call the get connection info method over HTTP. + + Args: + request (~.service.GetConnectionInfoRequest): + The request object. Request message for + GetConnectionInfo. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo', + }, + ] + request, metadata = self._interceptor.pre_get_connection_info(request, metadata) + pb_request = service.GetConnectionInfoRequest.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 = resources.ConnectionInfo() + pb_resp = resources.ConnectionInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connection_info(resp) + return resp + + class _GetInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetInstance") + + __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: service.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.service.GetInstanceRequest): + The request object. Message for getting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Instance: + An Instance is a computing unit that + an end customer can connect to. It's the + main unit of computing resources in + AlloyDB. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = service.GetInstanceRequest.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 = resources.Instance() + pb_resp = resources.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetUser") + + __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: service.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the get user method over HTTP. + + Args: + request (~.service.GetUserRequest): + The request object. Message for getting a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/clusters/*/users/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user(request, metadata) + pb_request = service.GetUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_user(resp) + return resp + + class _InjectFault(AlloyDBAdminRestStub): + def __hash__(self): + return hash("InjectFault") + + __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: service.InjectFaultRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the inject fault method over HTTP. + + Args: + request (~.service.InjectFaultRequest): + The request object. Message for triggering fault + injection on an instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_inject_fault(request, metadata) + pb_request = service.InjectFaultRequest.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_inject_fault(resp) + return resp + + class _ListBackups(AlloyDBAdminRestStub): + 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: service.ListBackupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.service.ListBackupsRequest): + The request object. Message for requesting list of + Backups + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListBackupsResponse: + Message for response to listing + Backups + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/backups', + }, + ] + request, metadata = self._interceptor.pre_list_backups(request, metadata) + pb_request = service.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 = service.ListBackupsResponse() + pb_resp = service.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_backups(resp) + return resp + + class _ListClusters(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListClusters") + + __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: service.ListClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListClustersResponse: + r"""Call the list clusters method over HTTP. + + Args: + request (~.service.ListClustersRequest): + The request object. Message for requesting list of + Clusters + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListClustersResponse: + Message for response to listing + Clusters + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/clusters', + }, + ] + request, metadata = self._interceptor.pre_list_clusters(request, metadata) + pb_request = service.ListClustersRequest.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 = service.ListClustersResponse() + pb_resp = service.ListClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_clusters(resp) + return resp + + class _ListInstances(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListInstances") + + __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: service.ListInstancesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.service.ListInstancesRequest): + The request object. Message for requesting list of + Instances + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListInstancesResponse: + Message for response to listing + Instances + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/clusters/*}/instances', + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = service.ListInstancesRequest.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 = service.ListInstancesResponse() + pb_resp = service.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListSupportedDatabaseFlags(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListSupportedDatabaseFlags") + + __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: service.ListSupportedDatabaseFlagsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListSupportedDatabaseFlagsResponse: + r"""Call the list supported database + flags method over HTTP. + + Args: + request (~.service.ListSupportedDatabaseFlagsRequest): + The request object. Message for listing the information + about the supported Database flags. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListSupportedDatabaseFlagsResponse: + Message for response to listing + SupportedDatabaseFlags. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/supportedDatabaseFlags', + }, + ] + request, metadata = self._interceptor.pre_list_supported_database_flags(request, metadata) + pb_request = service.ListSupportedDatabaseFlagsRequest.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 = service.ListSupportedDatabaseFlagsResponse() + pb_resp = service.ListSupportedDatabaseFlagsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_supported_database_flags(resp) + return resp + + class _ListUsers(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListUsers") + + __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: service.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.service.ListUsersRequest): + The request object. Message for requesting list of Users + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListUsersResponse: + Message for response to listing Users + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/clusters/*}/users', + }, + ] + request, metadata = self._interceptor.pre_list_users(request, metadata) + pb_request = service.ListUsersRequest.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 = service.ListUsersResponse() + pb_resp = service.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_users(resp) + return resp + + class _PromoteCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("PromoteCluster") + + __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: service.PromoteClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the promote cluster method over HTTP. + + Args: + request (~.service.PromoteClusterRequest): + The request object. Message for promoting a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{name=projects/*/locations/*/clusters/*}:promote', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_promote_cluster(request, metadata) + pb_request = service.PromoteClusterRequest.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_promote_cluster(resp) + return resp + + class _RestartInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestartInstance") + + __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: service.RestartInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restart instance method over HTTP. + + Args: + request (~.service.RestartInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + 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/{name=projects/*/locations/*/clusters/*/instances/*}:restart', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restart_instance(request, metadata) + pb_request = service.RestartInstanceRequest.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_restart_instance(resp) + return resp + + class _RestoreCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("RestoreCluster") + + __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: service.RestoreClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the restore cluster method over HTTP. + + Args: + request (~.service.RestoreClusterRequest): + The request object. Message for restoring a Cluster from + a backup or another cluster at a given + point in time. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/*}/clusters:restore', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restore_cluster(request, metadata) + pb_request = service.RestoreClusterRequest.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_cluster(resp) + return resp + + class _UpdateBackup(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateBackup") + + __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: service.UpdateBackupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update backup method over HTTP. + + Args: + request (~.service.UpdateBackupRequest): + The request object. Message for updating a Backup + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{backup.name=projects/*/locations/*/backups/*}', + 'body': 'backup', + }, + ] + request, metadata = self._interceptor.pre_update_backup(request, metadata) + pb_request = service.UpdateBackupRequest.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_backup(resp) + return resp + + class _UpdateCluster(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateCluster") + + __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: service.UpdateClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update cluster method over HTTP. + + Args: + request (~.service.UpdateClusterRequest): + The request object. Message for updating a Cluster + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{cluster.name=projects/*/locations/*/clusters/*}', + 'body': 'cluster', + }, + ] + request, metadata = self._interceptor.pre_update_cluster(request, metadata) + pb_request = service.UpdateClusterRequest.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_cluster(resp) + return resp + + class _UpdateInstance(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateInstance") + + __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: service.UpdateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. + + Args: + request (~.service.UpdateInstanceRequest): + The request object. Message for updating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_update_instance(request, metadata) + pb_request = service.UpdateInstanceRequest.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_instance(resp) + return resp + + class _UpdateUser(AlloyDBAdminRestStub): + def __hash__(self): + return hash("UpdateUser") + + __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: service.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.User: + r"""Call the update user method over HTTP. + + Args: + request (~.service.UpdateUserRequest): + The request object. Message for updating a User + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.User: + Message describing User object. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{user.name=projects/*/locations/*/clusters/*/users/*}', + 'body': 'user', + }, + ] + request, metadata = self._interceptor.pre_update_user(request, metadata) + pb_request = service.UpdateUserRequest.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 = resources.User() + pb_resp = resources.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_user(resp) + return resp + + @property + def batch_create_instances(self) -> Callable[ + [service.BatchCreateInstancesRequest], + 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._BatchCreateInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.CreateClusterRequest], + 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._CreateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_instance(self) -> Callable[ + [service.CreateInstanceRequest], + 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_cluster(self) -> Callable[ + [service.CreateSecondaryClusterRequest], + 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._CreateSecondaryCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_secondary_instance(self) -> Callable[ + [service.CreateSecondaryInstanceRequest], + 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._CreateSecondaryInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user(self) -> Callable[ + [service.CreateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup(self) -> Callable[ + [service.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_cluster(self) -> Callable[ + [service.DeleteClusterRequest], + 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._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance(self) -> Callable[ + [service.DeleteInstanceRequest], + 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [service.DeleteUserRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def failover_instance(self) -> Callable[ + [service.FailoverInstanceRequest], + 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._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_client_certificate(self) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateClientCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup(self) -> Callable[ + [service.GetBackupRequest], + resources.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_cluster(self) -> Callable[ + [service.GetClusterRequest], + resources.Cluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_connection_info(self) -> Callable[ + [service.GetConnectionInfoRequest], + resources.ConnectionInfo]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConnectionInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [service.GetInstanceRequest], + resources.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [service.GetUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def inject_fault(self) -> Callable[ + [service.InjectFaultRequest], + 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._InjectFault(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups(self) -> Callable[ + [service.ListBackupsRequest], + service.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_clusters(self) -> Callable[ + [service.ListClustersRequest], + service.ListClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances(self) -> Callable[ + [service.ListInstancesRequest], + service.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_supported_database_flags(self) -> Callable[ + [service.ListSupportedDatabaseFlagsRequest], + service.ListSupportedDatabaseFlagsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSupportedDatabaseFlags(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [service.ListUsersRequest], + service.ListUsersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def promote_cluster(self) -> Callable[ + [service.PromoteClusterRequest], + 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._PromoteCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def restart_instance(self) -> Callable[ + [service.RestartInstanceRequest], + 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._RestartInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_cluster(self) -> Callable[ + [service.RestoreClusterRequest], + 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._RestoreCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_backup(self) -> Callable[ + [service.UpdateBackupRequest], + 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._UpdateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cluster(self) -> Callable[ + [service.UpdateClusterRequest], + 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._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance(self) -> Callable[ + [service.UpdateInstanceRequest], + 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [service.UpdateUserRequest], + resources.User]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUser(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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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 cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(AlloyDBAdminRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_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_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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(AlloyDBAdminRestStub): + 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__=( + 'AlloyDBAdminRestTransport', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/__init__.py new file mode 100644 index 000000000000..b4ca84d7f24c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/__init__.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .resources import ( + AutomatedBackupPolicy, + Backup, + BackupSource, + Cluster, + ConnectionInfo, + ContinuousBackupConfig, + ContinuousBackupInfo, + ContinuousBackupSource, + EncryptionConfig, + EncryptionInfo, + Instance, + MigrationSource, + SslConfig, + SupportedDatabaseFlag, + User, + UserPassword, + ClusterView, + DatabaseVersion, + InstanceView, +) +from .service import ( + BatchCreateInstancesMetadata, + BatchCreateInstancesRequest, + BatchCreateInstancesResponse, + BatchCreateInstanceStatus, + CreateBackupRequest, + CreateClusterRequest, + CreateInstanceRequest, + CreateInstanceRequests, + CreateSecondaryClusterRequest, + CreateSecondaryInstanceRequest, + CreateUserRequest, + DeleteBackupRequest, + DeleteClusterRequest, + DeleteInstanceRequest, + DeleteUserRequest, + FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, + GetBackupRequest, + GetClusterRequest, + GetConnectionInfoRequest, + GetInstanceRequest, + GetUserRequest, + InjectFaultRequest, + ListBackupsRequest, + ListBackupsResponse, + ListClustersRequest, + ListClustersResponse, + ListInstancesRequest, + ListInstancesResponse, + ListSupportedDatabaseFlagsRequest, + ListSupportedDatabaseFlagsResponse, + ListUsersRequest, + ListUsersResponse, + OperationMetadata, + PromoteClusterRequest, + RestartInstanceRequest, + RestoreClusterRequest, + UpdateBackupRequest, + UpdateClusterRequest, + UpdateInstanceRequest, + UpdateUserRequest, +) + +__all__ = ( + 'AutomatedBackupPolicy', + 'Backup', + 'BackupSource', + 'Cluster', + 'ConnectionInfo', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'ContinuousBackupSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'Instance', + 'MigrationSource', + 'SslConfig', + 'SupportedDatabaseFlag', + 'User', + 'UserPassword', + 'ClusterView', + 'DatabaseVersion', + 'InstanceView', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstanceStatus', + 'CreateBackupRequest', + 'CreateClusterRequest', + 'CreateInstanceRequest', + 'CreateInstanceRequests', + 'CreateSecondaryClusterRequest', + 'CreateSecondaryInstanceRequest', + 'CreateUserRequest', + 'DeleteBackupRequest', + 'DeleteClusterRequest', + 'DeleteInstanceRequest', + 'DeleteUserRequest', + 'FailoverInstanceRequest', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetBackupRequest', + 'GetClusterRequest', + 'GetConnectionInfoRequest', + 'GetInstanceRequest', + 'GetUserRequest', + 'InjectFaultRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'ListClustersRequest', + 'ListClustersResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'ListUsersRequest', + 'ListUsersResponse', + 'OperationMetadata', + 'PromoteClusterRequest', + 'RestartInstanceRequest', + 'RestoreClusterRequest', + 'UpdateBackupRequest', + 'UpdateClusterRequest', + 'UpdateInstanceRequest', + 'UpdateUserRequest', +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/resources.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/resources.py new file mode 100644 index 000000000000..174168869942 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/resources.py @@ -0,0 +1,2011 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_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 +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1beta', + manifest={ + 'InstanceView', + 'ClusterView', + 'DatabaseVersion', + 'UserPassword', + 'MigrationSource', + 'EncryptionConfig', + 'EncryptionInfo', + 'SslConfig', + 'AutomatedBackupPolicy', + 'ContinuousBackupConfig', + 'ContinuousBackupInfo', + 'BackupSource', + 'ContinuousBackupSource', + 'Cluster', + 'Instance', + 'ConnectionInfo', + 'Backup', + 'SupportedDatabaseFlag', + 'User', + }, +) + + +class InstanceView(proto.Enum): + r"""View on Instance. Pass this enum to rpcs that returns an + Instance message to control which subsets of fields to get. + + Values: + INSTANCE_VIEW_UNSPECIFIED (0): + INSTANCE_VIEW_UNSPECIFIED Not specified, equivalent to + BASIC. + INSTANCE_VIEW_BASIC (1): + BASIC server responses for a primary or read + instance include all the relevant instance + details, excluding the details of each node in + the instance. The default value. + INSTANCE_VIEW_FULL (2): + FULL response is equivalent to BASIC for + primary instance (for now). For read pool + instance, this includes details of each node in + the pool. + """ + INSTANCE_VIEW_UNSPECIFIED = 0 + INSTANCE_VIEW_BASIC = 1 + INSTANCE_VIEW_FULL = 2 + + +class ClusterView(proto.Enum): + r"""View on Cluster. Pass this enum to rpcs that returns a + cluster message to control which subsets of fields to get. + + Values: + CLUSTER_VIEW_UNSPECIFIED (0): + CLUSTER_VIEW_UNSPECIFIED Not specified, equivalent to BASIC. + CLUSTER_VIEW_BASIC (1): + BASIC server responses include all the + relevant cluster details, excluding + Cluster.ContinuousBackupInfo.EarliestRestorableTime + and other view-specific fields. The default + value. + CLUSTER_VIEW_CONTINUOUS_BACKUP (2): + CONTINUOUS_BACKUP response returns all the fields from BASIC + plus the earliest restorable time if continuous backups are + enabled. May increase latency. + """ + CLUSTER_VIEW_UNSPECIFIED = 0 + CLUSTER_VIEW_BASIC = 1 + CLUSTER_VIEW_CONTINUOUS_BACKUP = 2 + + +class DatabaseVersion(proto.Enum): + r"""The supported database engine versions. + + Values: + DATABASE_VERSION_UNSPECIFIED (0): + This is an unknown database version. + POSTGRES_13 (1): + DEPRECATED - The database version is Postgres + 13. + POSTGRES_14 (2): + The database version is Postgres 14. + POSTGRES_15 (3): + The database version is Postgres 15. + """ + DATABASE_VERSION_UNSPECIFIED = 0 + POSTGRES_13 = 1 + POSTGRES_14 = 2 + POSTGRES_15 = 3 + + +class UserPassword(proto.Message): + r"""The username/password for a database user. Used for + specifying initial users at cluster creation time. + + Attributes: + user (str): + The database username. + password (str): + The initial password for the user. + """ + + user: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MigrationSource(proto.Message): + r"""Subset of the source instance configuration that is available + when reading the cluster resource. + + Attributes: + host_port (str): + Output only. The host and port of the + on-premises instance in host:port format + reference_id (str): + Output only. Place holder for the external + source identifier(e.g DMS job name) that created + the cluster. + source_type (google.cloud.alloydb_v1beta.types.MigrationSource.MigrationSourceType): + Output only. Type of migration source. + """ + class MigrationSourceType(proto.Enum): + r"""Denote the type of migration source that created this + cluster. + + Values: + MIGRATION_SOURCE_TYPE_UNSPECIFIED (0): + Migration source is unknown. + DMS (1): + DMS source means the cluster was created via + DMS migration job. + """ + MIGRATION_SOURCE_TYPE_UNSPECIFIED = 0 + DMS = 1 + + host_port: str = proto.Field( + proto.STRING, + number=1, + ) + reference_id: str = proto.Field( + proto.STRING, + number=2, + ) + source_type: MigrationSourceType = proto.Field( + proto.ENUM, + number=3, + enum=MigrationSourceType, + ) + + +class EncryptionConfig(proto.Message): + r"""EncryptionConfig describes the encryption config of a cluster + or a backup that is encrypted with a CMEK (customer-managed + encryption key). + + Attributes: + kms_key_name (str): + The fully-qualified resource name of the KMS key. Each Cloud + KMS key is regionalized and has the following format: + projects/[PROJECT]/locations/[REGION]/keyRings/[RING]/cryptoKeys/[KEY_NAME] + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptionInfo(proto.Message): + r"""EncryptionInfo describes the encryption information of a + cluster or a backup. + + Attributes: + encryption_type (google.cloud.alloydb_v1beta.types.EncryptionInfo.Type): + Output only. Type of encryption. + kms_key_versions (MutableSequence[str]): + Output only. Cloud KMS key versions that are + being used to protect the database or the + backup. + """ + class Type(proto.Enum): + r"""Possible encryption types. + + Values: + TYPE_UNSPECIFIED (0): + Encryption type not specified. Defaults to + GOOGLE_DEFAULT_ENCRYPTION. + GOOGLE_DEFAULT_ENCRYPTION (1): + The data is encrypted at rest with a key that + is fully managed by Google. No key version will + be populated. This is the default state. + CUSTOMER_MANAGED_ENCRYPTION (2): + The data is encrypted at rest with a key that + is managed by the customer. KMS key versions + will be populated. + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DEFAULT_ENCRYPTION = 1 + CUSTOMER_MANAGED_ENCRYPTION = 2 + + encryption_type: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class SslConfig(proto.Message): + r"""SSL configuration. + + Attributes: + ssl_mode (google.cloud.alloydb_v1beta.types.SslConfig.SslMode): + Optional. SSL mode. Specifies client-server + SSL/TLS connection behavior. + ca_source (google.cloud.alloydb_v1beta.types.SslConfig.CaSource): + Optional. Certificate Authority (CA) source. Only + CA_SOURCE_MANAGED is supported currently, and is the default + value. + """ + class SslMode(proto.Enum): + r"""SSL mode options. + + Values: + SSL_MODE_UNSPECIFIED (0): + SSL mode not specified. Defaults to ENCRYPTED_ONLY. + SSL_MODE_ALLOW (1): + SSL connections are optional. CA verification + not enforced. + SSL_MODE_REQUIRE (2): + SSL connections are required. CA verification + not enforced. Clients may use locally + self-signed certificates (default psql client + behavior). + SSL_MODE_VERIFY_CA (3): + SSL connections are required. CA verification + enforced. Clients must have certificates signed + by a Cluster CA, e.g. via + GenerateClientCertificate. + ALLOW_UNENCRYPTED_AND_ENCRYPTED (4): + SSL connections are optional. CA verification + not enforced. + ENCRYPTED_ONLY (5): + SSL connections are required. CA verification + not enforced. + """ + SSL_MODE_UNSPECIFIED = 0 + SSL_MODE_ALLOW = 1 + SSL_MODE_REQUIRE = 2 + SSL_MODE_VERIFY_CA = 3 + ALLOW_UNENCRYPTED_AND_ENCRYPTED = 4 + ENCRYPTED_ONLY = 5 + + class CaSource(proto.Enum): + r"""Certificate Authority (CA) source for SSL/TLS certificates. + + Values: + CA_SOURCE_UNSPECIFIED (0): + Certificate Authority (CA) source not specified. Defaults to + CA_SOURCE_MANAGED. + CA_SOURCE_MANAGED (1): + Certificate Authority (CA) managed by the + AlloyDB Cluster. + """ + CA_SOURCE_UNSPECIFIED = 0 + CA_SOURCE_MANAGED = 1 + + ssl_mode: SslMode = proto.Field( + proto.ENUM, + number=1, + enum=SslMode, + ) + ca_source: CaSource = proto.Field( + proto.ENUM, + number=2, + enum=CaSource, + ) + + +class AutomatedBackupPolicy(proto.Message): + r"""Message describing the user-specified automated backup + policy. + All fields in the automated backup policy are optional. Defaults + for each field are provided if they are not set. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + weekly_schedule (google.cloud.alloydb_v1beta.types.AutomatedBackupPolicy.WeeklySchedule): + Weekly schedule for the Backup. + + This field is a member of `oneof`_ ``schedule``. + time_based_retention (google.cloud.alloydb_v1beta.types.AutomatedBackupPolicy.TimeBasedRetention): + Time-based Backup retention policy. + + This field is a member of `oneof`_ ``retention``. + quantity_based_retention (google.cloud.alloydb_v1beta.types.AutomatedBackupPolicy.QuantityBasedRetention): + Quantity-based Backup retention policy to + retain recent backups. + + This field is a member of `oneof`_ ``retention``. + enabled (bool): + Whether automated automated backups are + enabled. If not set, defaults to true. + + This field is a member of `oneof`_ ``_enabled``. + backup_window (google.protobuf.duration_pb2.Duration): + The length of the time window during which a + backup can be taken. If a backup does not + succeed within this time window, it will be + canceled and considered failed. + + The backup window must be at least 5 minutes + long. There is no upper bound on the window. If + not set, it defaults to 1 hour. + encryption_config (google.cloud.alloydb_v1beta.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backups with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + location (str): + The location where the backup will be stored. + Currently, the only supported option is to store + the backup in the same region as the cluster. + + If empty, defaults to the region of the cluster. + labels (MutableMapping[str, str]): + Labels to apply to backups created using this + configuration. + """ + + class WeeklySchedule(proto.Message): + r"""A weekly schedule starts a backup at prescribed start times within a + day, for the specified days of the week. + + The weekly schedule message is flexible and can be used to create + many types of schedules. For example, to have a daily backup that + starts at 22:00, configure the ``start_times`` field to have one + element "22:00" and the ``days_of_week`` field to have all seven + days of the week. + + Attributes: + start_times (MutableSequence[google.type.timeofday_pb2.TimeOfDay]): + The times during the day to start a backup. + The start times are assumed to be in UTC and to + be an exact hour (e.g., 04:00:00). + + If no start times are provided, a single fixed + start time is chosen arbitrarily. + days_of_week (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + The days of the week to perform a backup. + + If this field is left empty, the default of + every day of the week is used. + """ + + start_times: MutableSequence[timeofday_pb2.TimeOfDay] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=timeofday_pb2.TimeOfDay, + ) + days_of_week: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + class TimeBasedRetention(proto.Message): + r"""A time based retention policy specifies that all backups + within a certain time period should be retained. + + Attributes: + retention_period (google.protobuf.duration_pb2.Duration): + The retention period. + """ + + retention_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class QuantityBasedRetention(proto.Message): + r"""A quantity based policy specifies that a certain number of + the most recent successful backups should be retained. + + Attributes: + count (int): + The number of backups to retain. + """ + + count: int = proto.Field( + proto.INT32, + number=1, + ) + + weekly_schedule: WeeklySchedule = proto.Field( + proto.MESSAGE, + number=2, + oneof='schedule', + message=WeeklySchedule, + ) + time_based_retention: TimeBasedRetention = proto.Field( + proto.MESSAGE, + number=4, + oneof='retention', + message=TimeBasedRetention, + ) + quantity_based_retention: QuantityBasedRetention = proto.Field( + proto.MESSAGE, + number=5, + oneof='retention', + message=QuantityBasedRetention, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + backup_window: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='EncryptionConfig', + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class ContinuousBackupConfig(proto.Message): + r"""ContinuousBackupConfig describes the continuous backups + recovery configurations of a cluster. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Whether ContinuousBackup is enabled. + + This field is a member of `oneof`_ ``_enabled``. + recovery_window_days (int): + The number of days that are eligible to + restore from using PITR. To support the entire + recovery window, backups and logs are retained + for one day more than the recovery window. If + not set, defaults to 14 days. + encryption_config (google.cloud.alloydb_v1beta.types.EncryptionConfig): + The encryption config can be specified to + encrypt the backups with a customer-managed + encryption key (CMEK). When this field is not + specified, the backup will then use default + encryption scheme to protect the user data. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + recovery_window_days: int = proto.Field( + proto.INT32, + number=4, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='EncryptionConfig', + ) + + +class ContinuousBackupInfo(proto.Message): + r"""ContinuousBackupInfo describes the continuous backup + properties of a cluster. + + Attributes: + encryption_info (google.cloud.alloydb_v1beta.types.EncryptionInfo): + Output only. The encryption information for + the WALs and backups required for + ContinuousBackup. + enabled_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When ContinuousBackup was most + recently enabled. Set to null if + ContinuousBackup is not enabled. + schedule (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + Output only. Days of the week on which a + continuous backup is taken. Output only field. + Ignored if passed into the request. + earliest_restorable_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The earliest restorable time + that can be restored to. Output only field. + """ + + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='EncryptionInfo', + ) + enabled_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + schedule: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=dayofweek_pb2.DayOfWeek, + ) + earliest_restorable_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class BackupSource(proto.Message): + r"""Message describing a BackupSource. + + Attributes: + backup_uid (str): + Output only. The system-generated UID of the + backup which was used to create this resource. + The UID is generated when the backup is created, + and it is retained until the backup is deleted. + backup_name (str): + Required. The name of the backup resource with the format: + + - projects/{project}/locations/{region}/backups/{backup_id} + """ + + backup_uid: str = proto.Field( + proto.STRING, + number=2, + ) + backup_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ContinuousBackupSource(proto.Message): + r"""Message describing a ContinuousBackupSource. + + Attributes: + cluster (str): + Required. The source cluster from which to + restore. This cluster must have continuous + backup enabled for this operation to succeed. + For the required format, see the comment on the + Cluster.name field. + point_in_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The point in time to restore to. + """ + + cluster: str = proto.Field( + proto.STRING, + number=1, + ) + point_in_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Cluster(proto.Message): + r"""A cluster is a collection of regional AlloyDB resources. It + can include a primary instance and one or more read pool + instances. All cluster resources share a storage layer, which + scales as needed. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1beta.types.BackupSource): + Output only. Cluster created from backup. + + This field is a member of `oneof`_ ``source``. + migration_source (google.cloud.alloydb_v1beta.types.MigrationSource): + Output only. Cluster created via DMS + migration. + + This field is a member of `oneof`_ ``source``. + name (str): + Output only. The name of the cluster resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + where the cluster ID segment should satisfy the regex + expression ``[a-z0-9-]+``. For more details see + https://google.aip.dev/122. The prefix of the cluster + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Cluster. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1beta.types.Cluster.State): + Output only. The current serving state of the + cluster. + cluster_type (google.cloud.alloydb_v1beta.types.Cluster.ClusterType): + Output only. The type of the cluster. This is an output-only + field and it's populated at the Cluster creation time or the + Cluster promotion time. The cluster type is determined by + which RPC was used to create the cluster (i.e. + ``CreateCluster`` vs. ``CreateSecondaryCluster`` + database_version (google.cloud.alloydb_v1beta.types.DatabaseVersion): + Optional. The database engine major version. + This is an optional field and it is populated at + the Cluster creation time. If a database version + is not supplied at cluster creation time, then a + default database version will be used. + network_config (google.cloud.alloydb_v1beta.types.Cluster.NetworkConfig): + + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project}/global/networks/{network_id}". This is + required to create a cluster. Deprecated, use + network_config.network instead. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Cluster does not + match the user's intended state, and the service + is actively updating the resource to reconcile + them. This can happen due to user-triggered + updates or system actions like failover or + maintenance. + initial_user (google.cloud.alloydb_v1beta.types.UserPassword): + Input only. Initial user to setup during cluster creation. + Required. If used in ``RestoreCluster`` this is ignored. + automated_backup_policy (google.cloud.alloydb_v1beta.types.AutomatedBackupPolicy): + The automated backup policy for this cluster. + + If no policy is provided then the default policy + will be used. If backups are supported for the + cluster, the default policy takes one backup a + day, has a backup window of 1 hour, and retains + backups for 14 days. For more information on the + defaults, consult the documentation for the + message type. + ssl_config (google.cloud.alloydb_v1beta.types.SslConfig): + SSL configuration for this AlloyDB cluster. + encryption_config (google.cloud.alloydb_v1beta.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the data disks and other + persistent data resources of a cluster with a + customer-managed encryption key (CMEK). When + this field is not specified, the cluster will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1beta.types.EncryptionInfo): + Output only. The encryption information for + the cluster. + continuous_backup_config (google.cloud.alloydb_v1beta.types.ContinuousBackupConfig): + Optional. Continuous backup configuration for + this cluster. + continuous_backup_info (google.cloud.alloydb_v1beta.types.ContinuousBackupInfo): + Output only. Continuous backup properties for + this cluster. + secondary_config (google.cloud.alloydb_v1beta.types.Cluster.SecondaryConfig): + Cross Region replication config specific to + SECONDARY cluster. + primary_config (google.cloud.alloydb_v1beta.types.Cluster.PrimaryConfig): + Output only. Cross Region replication config + specific to PRIMARY cluster. + """ + class State(proto.Enum): + r"""Cluster State + + Values: + STATE_UNSPECIFIED (0): + The state of the cluster is unknown. + READY (1): + The cluster is active and running. + STOPPED (2): + The cluster is stopped. All instances in the + cluster are stopped. Customers can start a + stopped cluster at any point and all their + instances will come back to life with same names + and IP resources. In this state, customer pays + for storage. + Associated backups could also be present in a + stopped cluster. + EMPTY (3): + The cluster is empty and has no associated + resources. All instances, associated storage and + backups have been deleted. + CREATING (4): + The cluster is being created. + DELETING (5): + The cluster is being deleted. + FAILED (6): + The creation of the cluster failed. + BOOTSTRAPPING (7): + The cluster is bootstrapping with data from + some other source. Direct mutations to the + cluster (e.g. adding read pool) are not allowed. + MAINTENANCE (8): + The cluster is under maintenance. AlloyDB + regularly performs maintenance and upgrades on + customer clusters. Updates on the cluster are + not allowed while the cluster is in this state. + PROMOTING (9): + The cluster is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + EMPTY = 3 + CREATING = 4 + DELETING = 5 + FAILED = 6 + BOOTSTRAPPING = 7 + MAINTENANCE = 8 + PROMOTING = 9 + + class ClusterType(proto.Enum): + r"""Type of Cluster + + Values: + CLUSTER_TYPE_UNSPECIFIED (0): + The type of the cluster is unknown. + PRIMARY (1): + Primary cluster that support read and write + operations. + SECONDARY (2): + Secondary cluster that is replicating from + another region. This only supports read. + """ + CLUSTER_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + SECONDARY = 2 + + class NetworkConfig(proto.Message): + r"""Metadata related to network configuration. + + Attributes: + network (str): + Required. The resource link for the VPC network in which + cluster resources are created and from which they are + accessible via Private IP. The network must belong to the + same project as the cluster. It is specified in the form: + "projects/{project_number}/global/networks/{network_id}". + This is required to create a cluster. + allocated_ip_range (str): + Optional. Name of the allocated IP range for the private IP + AlloyDB cluster, for example: + "google-managed-services-default". If set, the instance IPs + for this cluster will be created in the allocated range. The + range name must comply with RFC 1035. Specifically, the name + must be 1-63 characters long and match the regular + expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. Field name is + intended to be consistent with CloudSQL. + """ + + network: str = proto.Field( + proto.STRING, + number=1, + ) + allocated_ip_range: str = proto.Field( + proto.STRING, + number=2, + ) + + class SecondaryConfig(proto.Message): + r"""Configuration information for the secondary cluster. This + should be set if and only if the cluster is of type SECONDARY. + + Attributes: + primary_cluster_name (str): + The name of the primary cluster name with the format: + + - projects/{project}/locations/{region}/clusters/{cluster_id} + """ + + primary_cluster_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class PrimaryConfig(proto.Message): + r"""Configuration for the primary cluster. It has the list of + clusters that are replicating from this cluster. This should be + set if and only if the cluster is of type PRIMARY. + + Attributes: + secondary_cluster_names (MutableSequence[str]): + Output only. Names of the clusters that are + replicating from this cluster. + """ + + secondary_cluster_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + backup_source: 'BackupSource' = proto.Field( + proto.MESSAGE, + number=15, + oneof='source', + message='BackupSource', + ) + migration_source: 'MigrationSource' = proto.Field( + proto.MESSAGE, + number=16, + oneof='source', + message='MigrationSource', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + cluster_type: ClusterType = proto.Field( + proto.ENUM, + number=24, + enum=ClusterType, + ) + database_version: 'DatabaseVersion' = proto.Field( + proto.ENUM, + number=9, + enum='DatabaseVersion', + ) + network_config: NetworkConfig = proto.Field( + proto.MESSAGE, + number=29, + message=NetworkConfig, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=13, + ) + initial_user: 'UserPassword' = proto.Field( + proto.MESSAGE, + number=14, + message='UserPassword', + ) + automated_backup_policy: 'AutomatedBackupPolicy' = proto.Field( + proto.MESSAGE, + number=17, + message='AutomatedBackupPolicy', + ) + ssl_config: 'SslConfig' = proto.Field( + proto.MESSAGE, + number=18, + message='SslConfig', + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=19, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=20, + message='EncryptionInfo', + ) + continuous_backup_config: 'ContinuousBackupConfig' = proto.Field( + proto.MESSAGE, + number=27, + message='ContinuousBackupConfig', + ) + continuous_backup_info: 'ContinuousBackupInfo' = proto.Field( + proto.MESSAGE, + number=28, + message='ContinuousBackupInfo', + ) + secondary_config: SecondaryConfig = proto.Field( + proto.MESSAGE, + number=22, + message=SecondaryConfig, + ) + primary_config: PrimaryConfig = proto.Field( + proto.MESSAGE, + number=23, + message=PrimaryConfig, + ) + + +class Instance(proto.Message): + r"""An Instance is a computing unit that an end customer can + connect to. It's the main unit of computing resources in + AlloyDB. + + Attributes: + name (str): + Output only. The name of the instance resource with the + format: + + - projects/{project}/locations/{region}/clusters/{cluster_id}/instances/{instance_id} + where the cluster and instance ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the instance + resource name is the name of the parent resource: + - projects/{project}/locations/{region}/clusters/{cluster_id} + display_name (str): + User-settable and human-readable display name + for the Instance. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1beta.types.Instance.State): + Output only. The current serving state of the + instance. + instance_type (google.cloud.alloydb_v1beta.types.Instance.InstanceType): + Required. The type of the instance. Specified + at creation time. + machine_config (google.cloud.alloydb_v1beta.types.Instance.MachineConfig): + Configurations for the machines that host the + underlying database engine. + availability_type (google.cloud.alloydb_v1beta.types.Instance.AvailabilityType): + Availability type of an Instance. If empty, defaults to + REGIONAL for primary instances. For read pools, + availability_type is always UNSPECIFIED. Instances in the + read pools are evenly distributed across available zones + within the region (i.e. read pools with more than one node + will have a node in at least two zones). + gce_zone (str): + The Compute Engine zone that the instance + should serve from, per + https://cloud.google.com/compute/docs/regions-zones + This can ONLY be specified for ZONAL instances. + If present for a REGIONAL instance, an error + will be thrown. If this is absent for a ZONAL + instance, instance is created in a random zone + with available capacity. + database_flags (MutableMapping[str, str]): + Database flags. Set at instance level. + + - They are copied from primary instance on read instance + creation. + - Read instances can set new or override existing flags + that are relevant for reads, e.g. for enabling columnar + cache on a read instance. Flags set on read instance may + or may not be present on primary. + + This is a list of "key": "value" pairs. "key": The name of + the flag. These flags are passed at instance setup time, so + include both server options and system variables for + Postgres. Flags are specified with underscores, not hyphens. + "value": The value of the flag. Booleans are set to **on** + for true and **off** for false. This field must be omitted + if the flag doesn't take a value. + writable_node (google.cloud.alloydb_v1beta.types.Instance.Node): + Output only. This is set for the read-write + VM of the PRIMARY instance only. + nodes (MutableSequence[google.cloud.alloydb_v1beta.types.Instance.Node]): + Output only. List of available read-only VMs + in this instance, including the standby for a + PRIMARY instance. + query_insights_config (google.cloud.alloydb_v1beta.types.Instance.QueryInsightsInstanceConfig): + Configuration for query insights. + read_pool_config (google.cloud.alloydb_v1beta.types.Instance.ReadPoolConfig): + Read pool specific config. + ip_address (str): + Output only. The IP address for the Instance. + This is the connection endpoint for an end-user + application. + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation). Set + to true if the current state of Instance does + not match the user's intended state, and the + service is actively updating the resource to + reconcile them. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + update_policy (google.cloud.alloydb_v1beta.types.Instance.UpdatePolicy): + Update policy that will be applied during + instance update. This field is not persisted + when you update the instance. To use a + non-default update policy, you must + specify explicitly specify the value in each + update request. + client_connection_config (google.cloud.alloydb_v1beta.types.Instance.ClientConnectionConfig): + Optional. Client connection specific + configurations + """ + class State(proto.Enum): + r"""Instance State + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + READY (1): + The instance is active and running. + STOPPED (2): + The instance is stopped. Instance name and IP + resources are preserved. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + MAINTENANCE (5): + The instance is down for maintenance. + FAILED (6): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance. Note: Instances in this state would + tried to be auto-repaired. And Customers should + be able to restart, update or delete these + instances. + BOOTSTRAPPING (8): + Index 7 is used in the producer apis for ROLLED_BACK state. + Keeping that index unused in case that state also needs to + exposed via consumer apis in future. The instance has been + configured to sync data from some other source. + PROMOTING (9): + The instance is being promoted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + STOPPED = 2 + CREATING = 3 + DELETING = 4 + MAINTENANCE = 5 + FAILED = 6 + BOOTSTRAPPING = 8 + PROMOTING = 9 + + class InstanceType(proto.Enum): + r"""Type of an Instance + + Values: + INSTANCE_TYPE_UNSPECIFIED (0): + The type of the instance is unknown. + PRIMARY (1): + PRIMARY instances support read and write + operations. + READ_POOL (2): + READ POOL instances support read operations only. Each read + pool instance consists of one or more homogeneous nodes. + + - Read pool of size 1 can only have zonal availability. + - Read pools with node count of 2 or more can have regional + availability (nodes are present in 2 or more zones in a + region). + SECONDARY (3): + SECONDARY instances support read operations + only. SECONDARY instance is a cross-region read + replica + """ + INSTANCE_TYPE_UNSPECIFIED = 0 + PRIMARY = 1 + READ_POOL = 2 + SECONDARY = 3 + + class AvailabilityType(proto.Enum): + r"""The Availability type of an instance. Potential values: + + - ZONAL: The instance serves data from only one zone. Outages in + that zone affect instance availability. + - REGIONAL: The instance can serve data from more than one zone + in a region (it is highly available). + + Values: + AVAILABILITY_TYPE_UNSPECIFIED (0): + This is an unknown Availability type. + ZONAL (1): + Zonal available instance. + REGIONAL (2): + Regional (or Highly) available instance. + """ + AVAILABILITY_TYPE_UNSPECIFIED = 0 + ZONAL = 1 + REGIONAL = 2 + + class MachineConfig(proto.Message): + r"""MachineConfig describes the configuration of a machine. + + Attributes: + cpu_count (int): + The number of CPU's in the VM instance. + """ + + cpu_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class Node(proto.Message): + r"""Details of a single node in the instance. + Nodes in an AlloyDB instance are ephemereal, they can change + during update, failover, autohealing and resize operations. + + Attributes: + zone_id (str): + The Compute Engine zone of the VM e.g. + "us-central1-b". + id (str): + The identifier of the VM e.g. + "test-read-0601-407e52be-ms3l". + ip (str): + The private IP address of the VM e.g. + "10.57.0.34". + state (str): + Determined by state of the compute VM and + postgres-service health. Compute VM state can + have values listed in + https://cloud.google.com/compute/docs/instances/instance-life-cycle + and postgres-service health can have values: + HEALTHY and UNHEALTHY. + """ + + zone_id: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + ip: str = proto.Field( + proto.STRING, + number=3, + ) + state: str = proto.Field( + proto.STRING, + number=4, + ) + + class QueryInsightsInstanceConfig(proto.Message): + r"""QueryInsights Instance specific configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + record_application_tags (bool): + Record application tags for an instance. + This flag is turned "on" by default. + + This field is a member of `oneof`_ ``_record_application_tags``. + record_client_address (bool): + Record client address for an instance. Client + address is PII information. This flag is turned + "on" by default. + + This field is a member of `oneof`_ ``_record_client_address``. + query_string_length (int): + Query string length. The default value is + 1024. Any integer between 256 and 4500 is + considered valid. + query_plans_per_minute (int): + Number of query execution plans captured by + Insights per minute for all queries combined. + The default value is 5. Any integer between 0 + and 20 is considered valid. + + This field is a member of `oneof`_ ``_query_plans_per_minute``. + """ + + record_application_tags: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + record_client_address: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + query_string_length: int = proto.Field( + proto.UINT32, + number=4, + ) + query_plans_per_minute: int = proto.Field( + proto.UINT32, + number=5, + optional=True, + ) + + class ReadPoolConfig(proto.Message): + r"""Configuration for a read pool instance. + + Attributes: + node_count (int): + Read capacity, i.e. number of nodes in a read + pool instance. + """ + + node_count: int = proto.Field( + proto.INT32, + number=1, + ) + + class UpdatePolicy(proto.Message): + r"""Policy to be used while updating the instance. + + Attributes: + mode (google.cloud.alloydb_v1beta.types.Instance.UpdatePolicy.Mode): + Mode for updating the instance. + """ + class Mode(proto.Enum): + r"""Specifies the available modes of update. + + Values: + MODE_UNSPECIFIED (0): + Mode is unknown. + DEFAULT (1): + Least disruptive way to apply the update. + FORCE_APPLY (2): + Performs a forced update when applicable. + This will be fast but may incur a downtime. + """ + MODE_UNSPECIFIED = 0 + DEFAULT = 1 + FORCE_APPLY = 2 + + mode: 'Instance.UpdatePolicy.Mode' = proto.Field( + proto.ENUM, + number=1, + enum='Instance.UpdatePolicy.Mode', + ) + + class ClientConnectionConfig(proto.Message): + r"""Client connection configuration + + Attributes: + require_connectors (bool): + Optional. Configuration to enforce connectors + only (ex: AuthProxy) connections to the + database. + ssl_config (google.cloud.alloydb_v1beta.types.SslConfig): + Optional. SSL config option for this + instance. + """ + + require_connectors: bool = proto.Field( + proto.BOOL, + number=1, + ) + ssl_config: 'SslConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='SslConfig', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + instance_type: InstanceType = proto.Field( + proto.ENUM, + number=9, + enum=InstanceType, + ) + machine_config: MachineConfig = proto.Field( + proto.MESSAGE, + number=10, + message=MachineConfig, + ) + availability_type: AvailabilityType = proto.Field( + proto.ENUM, + number=11, + enum=AvailabilityType, + ) + gce_zone: str = proto.Field( + proto.STRING, + number=12, + ) + database_flags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + writable_node: Node = proto.Field( + proto.MESSAGE, + number=19, + message=Node, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=Node, + ) + query_insights_config: QueryInsightsInstanceConfig = proto.Field( + proto.MESSAGE, + number=21, + message=QueryInsightsInstanceConfig, + ) + read_pool_config: ReadPoolConfig = proto.Field( + proto.MESSAGE, + number=14, + message=ReadPoolConfig, + ) + ip_address: str = proto.Field( + proto.STRING, + number=15, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=16, + ) + etag: str = proto.Field( + proto.STRING, + number=17, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + update_policy: UpdatePolicy = proto.Field( + proto.MESSAGE, + number=22, + message=UpdatePolicy, + ) + client_connection_config: ClientConnectionConfig = proto.Field( + proto.MESSAGE, + number=23, + message=ClientConnectionConfig, + ) + + +class ConnectionInfo(proto.Message): + r"""ConnectionInfo singleton resource. + https://google.aip.dev/156 + + Attributes: + name (str): + The name of the ConnectionInfo singleton resource, e.g.: + projects/{project}/locations/{location}/clusters/\ */instances/*/connectionInfo + This field currently has no semantic meaning. + ip_address (str): + Output only. The private network IP address for the + Instance. This is the default IP for the instance and is + always created (even if enable_public_ip is set). This is + the connection endpoint for an end-user application. + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + instance_uid (str): + Output only. The unique ID of the Instance. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Backup(proto.Message): + r"""Message describing Backup object + + Attributes: + name (str): + Output only. The name of the backup resource with the + format: + + - projects/{project}/locations/{region}/backups/{backup_id} + where the cluster and backup ID segments should satisfy + the regex expression ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``, + e.g. 1-63 characters of lowercase letters, numbers, and + dashes, starting with a letter, and ending with a letter + or number. For more details see + https://google.aip.dev/122. The prefix of the backup + resource name is the name of the parent resource: + - projects/{project}/locations/{region} + display_name (str): + User-settable and human-readable display name + for the Backup. + uid (str): + Output only. The system-generated UID of the + resource. The UID is assigned when the resource + is created, and it is retained until it is + deleted. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time stamp + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time stamp + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Delete time stamp + labels (MutableMapping[str, str]): + Labels as key value pairs + state (google.cloud.alloydb_v1beta.types.Backup.State): + Output only. The current state of the backup. + type_ (google.cloud.alloydb_v1beta.types.Backup.Type): + The backup type, which suggests the trigger + for the backup. + description (str): + User-provided description of the backup. + cluster_uid (str): + Output only. The system-generated UID of the + cluster which was used to create this resource. + cluster_name (str): + Required. The full resource name of the backup source + cluster (e.g., + projects/{project}/locations/{region}/clusters/{cluster_id}). + reconciling (bool): + Output only. Reconciling + (https://google.aip.dev/128#reconciliation), if + true, indicates that the service is actively + updating the resource. This can happen due to + user-triggered updates or system actions like + failover or maintenance. + encryption_config (google.cloud.alloydb_v1beta.types.EncryptionConfig): + Optional. The encryption config can be + specified to encrypt the backup with a + customer-managed encryption key (CMEK). When + this field is not specified, the backup will + then use default encryption scheme to protect + the user data. + encryption_info (google.cloud.alloydb_v1beta.types.EncryptionInfo): + Output only. The encryption information for + the backup. + etag (str): + For Resource freshness validation + (https://google.aip.dev/154) + annotations (MutableMapping[str, str]): + Annotations to allow client tools to store + small amount of arbitrary data. This is distinct + from labels. https://google.aip.dev/128 + size_bytes (int): + Output only. The size of the backup in bytes. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which after the backup is eligible + to be garbage collected. It is the duration specified by the + backup's retention policy, added to the backup's + create_time. + expiry_quantity (google.cloud.alloydb_v1beta.types.Backup.QuantityBasedExpiry): + Output only. The QuantityBasedExpiry of the + backup, specified by the backup's retention + policy. Once the expiry quantity is over + retention, the backup is eligible to be garbage + collected. + database_version (google.cloud.alloydb_v1beta.types.DatabaseVersion): + Output only. The database engine major + version of the cluster this backup was created + from. Any restored cluster created from this + backup will have the same database version. + """ + class State(proto.Enum): + r"""Backup State + + Values: + STATE_UNSPECIFIED (0): + The state of the backup is unknown. + READY (1): + The backup is ready. + CREATING (2): + The backup is creating. + FAILED (3): + The backup failed. + DELETING (4): + The backup is being deleted. + """ + STATE_UNSPECIFIED = 0 + READY = 1 + CREATING = 2 + FAILED = 3 + DELETING = 4 + + class Type(proto.Enum): + r"""Backup Type + + Values: + TYPE_UNSPECIFIED (0): + Backup Type is unknown. + ON_DEMAND (1): + ON_DEMAND backups that were triggered by the customer (e.g., + not AUTOMATED). + AUTOMATED (2): + AUTOMATED backups triggered by the automated + backups scheduler pursuant to an automated + backup policy. + CONTINUOUS (3): + CONTINUOUS backups triggered by the automated + backups scheduler due to a continuous backup + policy. + """ + TYPE_UNSPECIFIED = 0 + ON_DEMAND = 1 + AUTOMATED = 2 + CONTINUOUS = 3 + + class QuantityBasedExpiry(proto.Message): + r"""A backup's position in a quantity-based retention queue, of backups + with the same source cluster and type, with length, retention, + specified by the backup's retention policy. Once the position is + greater than the retention, the backup is eligible to be garbage + collected. + + Example: 5 backups from the same source cluster and type with a + quantity-based retention of 3 and denoted by backup_id (position, + retention). + + Safe: backup_5 (1, 3), backup_4, (2, 3), backup_3 (3, 3). Awaiting + garbage collection: backup_2 (4, 3), backup_1 (5, 3) + + Attributes: + retention_count (int): + Output only. The backup's position among its + backups with the same source cluster and type, + by descending chronological order create + time(i.e. newest first). + total_retention_count (int): + Output only. The length of the quantity-based + queue, specified by the backup's retention + policy. + """ + + retention_count: int = proto.Field( + proto.INT32, + number=1, + ) + total_retention_count: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + type_: Type = proto.Field( + proto.ENUM, + number=8, + enum=Type, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + cluster_uid: str = proto.Field( + proto.STRING, + number=18, + ) + cluster_name: str = proto.Field( + proto.STRING, + number=10, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=11, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='EncryptionConfig', + ) + encryption_info: 'EncryptionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='EncryptionInfo', + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=16, + ) + size_bytes: int = proto.Field( + proto.INT64, + number=17, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + expiry_quantity: QuantityBasedExpiry = proto.Field( + proto.MESSAGE, + number=20, + message=QuantityBasedExpiry, + ) + database_version: 'DatabaseVersion' = proto.Field( + proto.ENUM, + number=22, + enum='DatabaseVersion', + ) + + +class SupportedDatabaseFlag(proto.Message): + r"""SupportedDatabaseFlag gives general information about a database + flag, like type and allowed values. This is a static value that is + defined on the server side, and it cannot be modified by callers. To + set the Database flags on a particular Instance, a caller should + modify the Instance.database_flags field. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_restrictions (google.cloud.alloydb_v1beta.types.SupportedDatabaseFlag.StringRestrictions): + Restriction on STRING type value. + + This field is a member of `oneof`_ ``restrictions``. + integer_restrictions (google.cloud.alloydb_v1beta.types.SupportedDatabaseFlag.IntegerRestrictions): + Restriction on INTEGER type value. + + This field is a member of `oneof`_ ``restrictions``. + name (str): + The name of the flag resource, following Google Cloud + conventions, e.g.: + + - projects/{project}/locations/{location}/flags/{flag} This + field currently has no semantic meaning. + flag_name (str): + The name of the database flag, e.g. "max_allowed_packets". + The is a possibly key for the Instance.database_flags map + field. + value_type (google.cloud.alloydb_v1beta.types.SupportedDatabaseFlag.ValueType): + + accepts_multiple_values (bool): + Whether the database flag accepts multiple + values. If true, a comma-separated list of + stringified values may be specified. + supported_db_versions (MutableSequence[google.cloud.alloydb_v1beta.types.DatabaseVersion]): + Major database engine versions for which this + flag is supported. + requires_db_restart (bool): + Whether setting or updating this flag on an + Instance requires a database restart. If a flag + that requires database restart is set, the + backend will automatically restart the database + (making sure to satisfy any availability SLO's). + """ + class ValueType(proto.Enum): + r"""ValueType describes the semantic type of the value that the flag + accepts. Regardless of the ValueType, the Instance.database_flags + field accepts the stringified version of the value, i.e. "20" or + "3.14". + + Values: + VALUE_TYPE_UNSPECIFIED (0): + This is an unknown flag type. + STRING (1): + String type flag. + INTEGER (2): + Integer type flag. + FLOAT (3): + Float type flag. + NONE (4): + Denotes that the flag does not accept any + values. + """ + VALUE_TYPE_UNSPECIFIED = 0 + STRING = 1 + INTEGER = 2 + FLOAT = 3 + NONE = 4 + + class StringRestrictions(proto.Message): + r"""Restrictions on STRING type values + + Attributes: + allowed_values (MutableSequence[str]): + The list of allowed values, if bounded. This + field will be empty if there is a unbounded + number of allowed values. + """ + + allowed_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class IntegerRestrictions(proto.Message): + r"""Restrictions on INTEGER type values. + + Attributes: + min_value (google.protobuf.wrappers_pb2.Int64Value): + The minimum value that can be specified, if + applicable. + max_value (google.protobuf.wrappers_pb2.Int64Value): + The maximum value that can be specified, if + applicable. + """ + + min_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=1, + message=wrappers_pb2.Int64Value, + ) + max_value: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + + string_restrictions: StringRestrictions = proto.Field( + proto.MESSAGE, + number=7, + oneof='restrictions', + message=StringRestrictions, + ) + integer_restrictions: IntegerRestrictions = proto.Field( + proto.MESSAGE, + number=8, + oneof='restrictions', + message=IntegerRestrictions, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + flag_name: str = proto.Field( + proto.STRING, + number=2, + ) + value_type: ValueType = proto.Field( + proto.ENUM, + number=3, + enum=ValueType, + ) + accepts_multiple_values: bool = proto.Field( + proto.BOOL, + number=4, + ) + supported_db_versions: MutableSequence['DatabaseVersion'] = proto.RepeatedField( + proto.ENUM, + number=5, + enum='DatabaseVersion', + ) + requires_db_restart: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class User(proto.Message): + r"""Message describing User object. + + Attributes: + name (str): + Output only. Name of the resource in the form + of + projects/{project}/locations/{location}/cluster/{cluster}/users/{user}. + password (str): + Input only. Password for the user. + database_roles (MutableSequence[str]): + Optional. List of database roles this user + has. The database role strings are subject to + the PostgreSQL naming conventions. + user_type (google.cloud.alloydb_v1beta.types.User.UserType): + Optional. Type of this user. + """ + class UserType(proto.Enum): + r"""Enum that details the user type. + + Values: + USER_TYPE_UNSPECIFIED (0): + Unspecified user type. + ALLOYDB_BUILT_IN (1): + The default user type that authenticates via + password-based authentication. + ALLOYDB_IAM_USER (2): + Database user that can authenticate via + IAM-Based authentication. + """ + USER_TYPE_UNSPECIFIED = 0 + ALLOYDB_BUILT_IN = 1 + ALLOYDB_IAM_USER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + password: str = proto.Field( + proto.STRING, + number=2, + ) + database_roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + user_type: UserType = proto.Field( + proto.ENUM, + number=5, + enum=UserType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/service.py b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/service.py new file mode 100644 index 000000000000..e380273de47b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/google/cloud/alloydb_v1beta/types/service.py @@ -0,0 +1,2132 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.alloydb_v1beta.types import resources +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.alloydb.v1beta', + manifest={ + 'ListClustersRequest', + 'ListClustersResponse', + 'GetClusterRequest', + 'CreateSecondaryClusterRequest', + 'CreateClusterRequest', + 'UpdateClusterRequest', + 'DeleteClusterRequest', + 'PromoteClusterRequest', + 'RestoreClusterRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'CreateInstanceRequest', + 'CreateSecondaryInstanceRequest', + 'CreateInstanceRequests', + 'BatchCreateInstancesRequest', + 'BatchCreateInstancesResponse', + 'BatchCreateInstancesMetadata', + 'BatchCreateInstanceStatus', + 'UpdateInstanceRequest', + 'DeleteInstanceRequest', + 'FailoverInstanceRequest', + 'InjectFaultRequest', + 'RestartInstanceRequest', + 'ListBackupsRequest', + 'ListBackupsResponse', + 'GetBackupRequest', + 'CreateBackupRequest', + 'UpdateBackupRequest', + 'DeleteBackupRequest', + 'ListSupportedDatabaseFlagsRequest', + 'ListSupportedDatabaseFlagsResponse', + 'GenerateClientCertificateRequest', + 'GenerateClientCertificateResponse', + 'GetConnectionInfoRequest', + 'OperationMetadata', + 'ListUsersRequest', + 'ListUsersResponse', + 'GetUserRequest', + 'CreateUserRequest', + 'UpdateUserRequest', + 'DeleteUserRequest', + }, +) + + +class ListClustersRequest(proto.Message): + r"""Message for requesting list of Clusters + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Cluster.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with the following format: + + - projects/{project}/locations/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListClustersResponse(proto.Message): + r"""Message for response to listing Clusters + + Attributes: + clusters (MutableSequence[google.cloud.alloydb_v1beta.types.Cluster]): + The list of Cluster + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + clusters: MutableSequence[resources.Cluster] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Cluster, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetClusterRequest(proto.Message): + r"""Message for getting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + view (google.cloud.alloydb_v1beta.types.ClusterView): + Optional. The view of the cluster to return. + Returns all default fields if not set. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.ClusterView = proto.Field( + proto.ENUM, + number=2, + enum=resources.ClusterView, + ) + + +class CreateSecondaryClusterRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object (the + secondary cluster). + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. Configuration of the requesting + object (the secondary cluster). + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class CreateClusterRequest(proto.Message): + r"""Message for creating a Cluster + + Attributes: + parent (str): + Required. The location of the new cluster. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateClusterRequest(proto.Message): + r"""Message for updating a Cluster + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Cluster resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if cluster is + not found. In that case, a new cluster is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteClusterRequest(proto.Message): + r"""Message for deleting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + force (bool): + Optional. Whether to cascade delete child + instances for given cluster. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PromoteClusterRequest(proto.Message): + r"""Message for promoting a Cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Cluster. + If an etag is provided and does not match the + current etag of the Cluster, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestoreClusterRequest(proto.Message): + r"""Message for restoring a Cluster from a backup or another + cluster at a given point in time. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_source (google.cloud.alloydb_v1beta.types.BackupSource): + Backup source. + + This field is a member of `oneof`_ ``source``. + continuous_backup_source (google.cloud.alloydb_v1beta.types.ContinuousBackupSource): + ContinuousBackup source. Continuous backup + needs to be enabled in the source cluster for + this operation to succeed. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Cluster.name field. + cluster_id (str): + Required. ID of the requesting object. + cluster (google.cloud.alloydb_v1beta.types.Cluster): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + import request. + """ + + backup_source: resources.BackupSource = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message=resources.BackupSource, + ) + continuous_backup_source: resources.ContinuousBackupSource = proto.Field( + proto.MESSAGE, + number=8, + oneof='source', + message=resources.ContinuousBackupSource, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: resources.Cluster = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Cluster, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances + + Attributes: + parent (str): + Required. The name of the parent resource. For the required + format, see the comment on the Instance.name field. + Additionally, you can perform an aggregated list operation + by specifying a value with one of the following formats: + + - projects/{project}/locations/-/clusters/- + - projects/{project}/locations/{region}/clusters/- + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1beta.types.Instance]): + The list of Instance + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Message for getting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + view (google.cloud.alloydb_v1beta.types.InstanceView): + The view of the instance to return. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: resources.InstanceView = proto.Field( + proto.ENUM, + number=2, + enum=resources.InstanceView, + ) + + +class CreateInstanceRequest(proto.Message): + r"""Message for creating a Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateSecondaryInstanceRequest(proto.Message): + r"""Message for creating a Secondary Instance + + Attributes: + parent (str): + Required. The name of the parent resource. + For the required format, see the comment on the + Instance.name field. + instance_id (str): + Required. ID of the requesting object. + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + create request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateInstanceRequests(proto.Message): + r"""See usage below for notes. + + Attributes: + create_instance_requests (MutableSequence[google.cloud.alloydb_v1beta.types.CreateInstanceRequest]): + Required. Primary and read replica instances + to be created. This list should not be empty. + """ + + create_instance_requests: MutableSequence['CreateInstanceRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CreateInstanceRequest', + ) + + +class BatchCreateInstancesRequest(proto.Message): + r"""Message for creating a batch of instances under the specified + cluster. + + Attributes: + parent (str): + Required. The name of the parent resource. + requests (google.cloud.alloydb_v1beta.types.CreateInstanceRequests): + Required. Resources being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: 'CreateInstanceRequests' = proto.Field( + proto.MESSAGE, + number=2, + message='CreateInstanceRequests', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchCreateInstancesResponse(proto.Message): + r"""Message for creating batches of instances in a cluster. + + Attributes: + instances (MutableSequence[google.cloud.alloydb_v1beta.types.Instance]): + Created instances. + """ + + instances: MutableSequence[resources.Instance] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Instance, + ) + + +class BatchCreateInstancesMetadata(proto.Message): + r"""Message for metadata that is specific to BatchCreateInstances API. + NEXT_ID: 3 + + Attributes: + instance_targets (MutableSequence[str]): + The instances being created in the API call. + Each string in this list is the server defined + resource path for target instances in the + request and for the format of each string, see + the comment on the Instance.name field. + instance_statuses (MutableMapping[str, google.cloud.alloydb_v1beta.types.BatchCreateInstanceStatus]): + A map representing state of the instances involved in the + BatchCreateInstances operation during the operation + execution. The instance state will be in STATE_UNSPECIFIED + state if the instance has not yet been picked up for + processing. The key of the map is the name of the instance + resource. For the format, see the comment on the + Instance.name field. + """ + + instance_targets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + instance_statuses: MutableMapping[str, 'BatchCreateInstanceStatus'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='BatchCreateInstanceStatus', + ) + + +class BatchCreateInstanceStatus(proto.Message): + r"""Message for current status of an instance in the + BatchCreateInstances operation. For example, lets say a + BatchCreateInstances workflow has 4 instances, Instance1 through + Instance4. Lets also assume that 2 instances succeeded but the third + failed to create and the 4th was never picked up for creation + because of failure of the previous one. Then, resulting states would + look something like: + + 1. Instance1 = ROLLED_BACK + 2. Instance2 = ROLLED_BACK + 3. Instance3 = FAILED + 4. Instance4 = FAILED + + However, while the operation is running, the instance might be in + other states including PENDING_CREATE, ACTIVE, DELETING and + CREATING. The states / do not get further updated once the operation + is done. + + Attributes: + state (google.cloud.alloydb_v1beta.types.BatchCreateInstanceStatus.State): + The current state of an instance involved in the batch + create operation. Once the operation is complete, the final + state of the instances in the LRO can be one of: + + 1. ACTIVE, indicating that instances were created + successfully + 2. FAILED, indicating that a particular instance failed + creation + 3. ROLLED_BACK indicating that although the instance was + created successfully, it had to be rolled back and + deleted due to failure in other steps of the workflow. + error_msg (str): + DEPRECATED - Use the error field instead. + Error, if any error occurred and is available, + during instance creation. + error (google.rpc.status_pb2.Status): + The RPC status of the instance creation + operation. This field will be present if an + error happened during the instance creation. + type_ (google.cloud.alloydb_v1beta.types.Instance.InstanceType): + + """ + class State(proto.Enum): + r"""State contains all valid instance states for the + BatchCreateInstances operation. This is mainly used for status + reporting through the LRO metadata. + + Values: + STATE_UNSPECIFIED (0): + The state of the instance is unknown. + PENDING_CREATE (1): + Instance is pending creation and has not yet + been picked up for processsing in the backend. + READY (2): + The instance is active and running. + CREATING (3): + The instance is being created. + DELETING (4): + The instance is being deleted. + FAILED (5): + The creation of the instance failed or a + fatal error occurred during an operation on the + instance or a batch of instances. + ROLLED_BACK (6): + The instance was created successfully, but + was rolled back and deleted due to some other + failure during BatchCreateInstances operation. + """ + STATE_UNSPECIFIED = 0 + PENDING_CREATE = 1 + READY = 2 + CREATING = 3 + DELETING = 4 + FAILED = 5 + ROLLED_BACK = 6 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + error_msg: str = proto.Field( + proto.STRING, + number=2, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + type_: resources.Instance.InstanceType = proto.Field( + proto.ENUM, + number=3, + enum=resources.Instance.InstanceType, + ) + + +class UpdateInstanceRequest(proto.Message): + r"""Message for updating a Instance + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Instance resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + instance (google.cloud.alloydb_v1beta.types.Instance): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + update request. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new instance is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: resources.Instance = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Instance, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Message for deleting a Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + etag (str): + Optional. The current etag of the Instance. + If an etag is provided and does not match the + current etag of the Instance, deletion will be + blocked and an ABORTED error will be returned. + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class FailoverInstanceRequest(proto.Message): + r"""Message for triggering failover on an Instance + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + failover. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class InjectFaultRequest(proto.Message): + r"""Message for triggering fault injection on an instance + + Attributes: + fault_type (google.cloud.alloydb_v1beta.types.InjectFaultRequest.FaultType): + Required. The type of fault to be injected in + an instance. + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + fault injection. + """ + class FaultType(proto.Enum): + r"""FaultType contains all valid types of faults that can be + injected to an instance. + + Values: + FAULT_TYPE_UNSPECIFIED (0): + The fault type is unknown. + STOP_VM (1): + Stop the VM + """ + FAULT_TYPE_UNSPECIFIED = 0 + STOP_VM = 1 + + fault_type: FaultType = proto.Field( + proto.ENUM, + number=1, + enum=FaultType, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class RestartInstanceRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Instance.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, performs request validation + (e.g. permission checks and any other type of + validation), but do not actually execute the + restart. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListBackupsRequest(proto.Message): + r"""Message for requesting list of Backups + + Attributes: + parent (str): + Required. Parent value for ListBackupsRequest + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + filter (str): + Filtering results + order_by (str): + Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListBackupsResponse(proto.Message): + r"""Message for response to listing Backups + + Attributes: + backups (MutableSequence[google.cloud.alloydb_v1beta.types.Backup]): + The list of Backup + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence[resources.Backup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.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"""Message for getting a Backup + + Attributes: + name (str): + Required. Name of the resource + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateBackupRequest(proto.Message): + r"""Message for creating a Backup + + Attributes: + parent (str): + Required. Value for parent. + backup_id (str): + Required. ID of the requesting object. + backup (google.cloud.alloydb_v1beta.types.Backup): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=3, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateBackupRequest(proto.Message): + r"""Message for updating a Backup + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + backup (google.cloud.alloydb_v1beta.types.Backup): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. If set to true, update succeeds even if instance + is not found. In that case, a new backup is created and + ``update_mask`` is ignored. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + backup: resources.Backup = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Backup, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Message for deleting a Backup + + Attributes: + name (str): + Required. Name of the resource. For the + required format, see the comment on the + Backup.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + etag (str): + Optional. The current etag of the Backup. + If an etag is provided and does not match the + current etag of the Backup, deletion will be + blocked and an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSupportedDatabaseFlagsRequest(proto.Message): + r"""Message for listing the information about the supported + Database flags. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location} + + Regardless of the parent specified here, as long it is + contains a valid project and location, the service will + return a static list of supported flags resources. Note that + we do not yet support region-specific flags. + page_size (int): + Requested page size. Server may return fewer + items than requested. If unspecified, server + will pick an appropriate default. + page_token (str): + A token identifying a page of results the + server should return. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSupportedDatabaseFlagsResponse(proto.Message): + r"""Message for response to listing SupportedDatabaseFlags. + + Attributes: + supported_database_flags (MutableSequence[google.cloud.alloydb_v1beta.types.SupportedDatabaseFlag]): + The list of SupportedDatabaseFlags. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + supported_database_flags: MutableSequence[resources.SupportedDatabaseFlag] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.SupportedDatabaseFlag, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateClientCertificateRequest(proto.Message): + r"""Message for requests to generate a client certificate signed + by the Cluster CA. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + pem_csr (str): + Optional. A pem-encoded X.509 certificate + signing request (CSR). + cert_duration (google.protobuf.duration_pb2.Duration): + Optional. An optional hint to the endpoint to + generate the client certificate with the + requested duration. The duration can be from 1 + hour to 24 hours. The endpoint may or may not + honor the hint. If the hint is left unspecified + or is not honored, then the endpoint will pick + an appropriate default duration. + public_key (str): + Optional. The public key from the client. + use_metadata_exchange (bool): + Optional. An optional hint to the endpoint to + generate a client ceritificate that can be used + by AlloyDB connectors to exchange additional + metadata with the server after TLS handshake. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + pem_csr: str = proto.Field( + proto.STRING, + number=3, + ) + cert_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + public_key: str = proto.Field( + proto.STRING, + number=5, + ) + use_metadata_exchange: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class GenerateClientCertificateResponse(proto.Message): + r"""Message returned by a GenerateClientCertificate operation. + + Attributes: + pem_certificate (str): + Output only. The pem-encoded, signed X.509 + certificate. + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + ca_cert (str): + Optional. The pem-encoded cluster ca X.509 + certificate. + """ + + pem_certificate: str = proto.Field( + proto.STRING, + number=1, + ) + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + ca_cert: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetConnectionInfoRequest(proto.Message): + r"""Request message for GetConnectionInfo. + + Attributes: + parent (str): + Required. The name of the parent resource. + The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + batch_create_instances_metadata (google.cloud.alloydb_v1beta.types.BatchCreateInstancesMetadata): + Output only. BatchCreateInstances related + metadata. + + This field is a member of `oneof`_ ``request_specific``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + 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. + """ + + batch_create_instances_metadata: 'BatchCreateInstancesMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='request_specific', + message='BatchCreateInstancesMetadata', + ) + 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 ListUsersRequest(proto.Message): + r"""Message for requesting list of Users + + Attributes: + parent (str): + Required. Parent value for ListUsersRequest + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListUsersResponse(proto.Message): + r"""Message for response to listing Users + + Attributes: + users (MutableSequence[google.cloud.alloydb_v1beta.types.User]): + The list of User + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence[resources.User] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.User, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetUserRequest(proto.Message): + r"""Message for getting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserRequest(proto.Message): + r"""Message for creating a User + + Attributes: + parent (str): + Required. Value for parent. + user_id (str): + Required. ID of the requesting object. + user (google.cloud.alloydb_v1beta.types.User): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=3, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateUserRequest(proto.Message): + r"""Message for updating a User + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the User resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then all + fields will be overwritten. + user (google.cloud.alloydb_v1beta.types.User): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + allow_missing (bool): + Optional. Allow missing fields in the update + mask. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + user: resources.User = proto.Field( + proto.MESSAGE, + number=2, + message=resources.User, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class DeleteUserRequest(proto.Message): + r"""Message for deleting a User + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + User.name field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. If set, the backend validates the + request, but doesn't actually execute it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/mypy.ini b/owl-bot-staging/google-cloud-alloydb/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/noxfile.py b/owl-bot-staging/google-cloud-alloydb/v1beta/noxfile.py new file mode 100644 index 000000000000..16f26d7e7c59 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/alloydb_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==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_async.py new file mode 100644 index 000000000000..5bebd08fb469 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1beta + + +async def sample_batch_create_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + requests = alloydb_v1beta.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_sync.py new file mode 100644 index 000000000000..854b188ed8dd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_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 alloydb_v1beta + + +def sample_batch_create_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + requests = alloydb_v1beta.CreateInstanceRequests() + requests.create_instance_requests.parent = "parent_value" + requests.create_instance_requests.instance_id = "instance_id_value" + requests.create_instance_requests.instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.BatchCreateInstancesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + operation = client.batch_create_instances(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_async.py new file mode 100644 index 000000000000..d1bceb260ae7 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +async def sample_create_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # 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 alloydb_v1beta_generated_AlloyDBAdmin_CreateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_sync.py new file mode 100644 index 000000000000..d33ca6e7d8b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_backup_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +def sample_create_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + backup=backup, + ) + + # Make the request + operation = client.create_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_async.py new file mode 100644 index 000000000000..c45957af4852 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1beta + + +async def sample_create_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_sync.py new file mode 100644 index 000000000000..c64656cba074 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_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 alloydb_v1beta + + +def sample_create_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_async.py new file mode 100644 index 000000000000..76bedcdf597b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1beta + + +async def sample_create_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_sync.py new file mode 100644 index 000000000000..77d481868079 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_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 alloydb_v1beta + + +def sample_create_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_async.py new file mode 100644 index 000000000000..a7da3d06012e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1beta + + +async def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_sync.py new file mode 100644 index 000000000000..965d8dc5dbff --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_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 alloydb_v1beta + + +def sample_create_secondary_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.CreateSecondaryClusterRequest( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.create_secondary_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_async.py new file mode 100644 index 000000000000..62b6443dd241 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1beta + + +async def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_sync.py new file mode 100644 index 000000000000..87887a03f6d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecondaryInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_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 alloydb_v1beta + + +def sample_create_secondary_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_secondary_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_async.py new file mode 100644 index 000000000000..666045d84ef5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1beta + + +async def sample_create_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_sync.py new file mode 100644 index 000000000000..85d9fc92d587 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_create_user_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_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 alloydb_v1beta + + +def sample_create_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_async.py new file mode 100644 index 000000000000..0dd5c3d88646 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +async def sample_delete_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1beta_generated_AlloyDBAdmin_DeleteBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_sync.py new file mode 100644 index 000000000000..5fa6b84a07cf --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_backup_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +def sample_delete_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1beta_generated_AlloyDBAdmin_DeleteBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_async.py new file mode 100644 index 000000000000..dd08c1fb54b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1beta + + +async def sample_delete_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_sync.py new file mode 100644 index 000000000000..f30bff39682a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_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 alloydb_v1beta + + +def sample_delete_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_async.py new file mode 100644 index 000000000000..b9fe7fec64cc --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1beta + + +async def sample_delete_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_sync.py new file mode 100644 index 000000000000..d80bb5770508 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_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 alloydb_v1beta + + +def sample_delete_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_async.py new file mode 100644 index 000000000000..9c0f1b932a5d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1beta + + +async def sample_delete_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_sync.py new file mode 100644 index 000000000000..21fa38edeaa0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_delete_user_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_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 alloydb_v1beta + + +def sample_delete_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_async.py new file mode 100644 index 000000000000..abb628c1e773 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1beta + + +async def sample_failover_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_sync.py new file mode 100644 index 000000000000..2264c5531565 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_failover_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_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 alloydb_v1beta + + +def sample_failover_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.FailoverInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.failover_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_async.py new file mode 100644 index 000000000000..f1d54b369e79 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_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 alloydb_v1beta + + +async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_sync.py new file mode 100644 index 000000000000..3e63960a4240 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_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 alloydb_v1beta + + +def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_async.py new file mode 100644 index 000000000000..9a4a9a75d0a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +async def sample_get_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_sync.py new file mode 100644 index 000000000000..97b6d7286ed3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_backup_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +def sample_get_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_async.py new file mode 100644 index 000000000000..d80fd36c971c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1beta + + +async def sample_get_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_sync.py new file mode 100644 index 000000000000..18ef3b65c6bd --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_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 alloydb_v1beta + + +def sample_get_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_cluster(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_async.py new file mode 100644 index 000000000000..7d55aff0d143 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_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 alloydb_v1beta + + +async def sample_get_connection_info(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_sync.py new file mode 100644 index 000000000000..56c35cfeced8 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_connection_info_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_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 alloydb_v1beta + + +def sample_get_connection_info(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_async.py new file mode 100644 index 000000000000..65ae654aa937 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1beta + + +async def sample_get_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_sync.py new file mode 100644 index 000000000000..7fb8ef553bad --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_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 alloydb_v1beta + + +def sample_get_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_async.py new file mode 100644 index 000000000000..2b7cbb61878d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetUser_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 alloydb_v1beta + + +async def sample_get_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_sync.py new file mode 100644 index 000000000000..38a2136ad95c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_get_user_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_GetUser_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 alloydb_v1beta + + +def sample_get_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_GetUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_async.py new file mode 100644 index 000000000000..bdd154e944fb --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1beta + + +async def sample_inject_fault(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_sync.py new file mode 100644 index 000000000000..d0f48fa0755e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_inject_fault_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InjectFault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_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 alloydb_v1beta + + +def sample_inject_fault(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.InjectFaultRequest( + fault_type="STOP_VM", + name="name_value", + ) + + # Make the request + operation = client.inject_fault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_async.py new file mode 100644 index 000000000000..c99c03bde602 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +async def sample_list_backups(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1beta_generated_AlloyDBAdmin_ListBackups_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_sync.py new file mode 100644 index 000000000000..75d52679ff46 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_backups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_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 alloydb_v1beta + + +def sample_list_backups(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_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 alloydb_v1beta_generated_AlloyDBAdmin_ListBackups_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_async.py new file mode 100644 index 000000000000..1fa130554c8f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1beta + + +async def sample_list_clusters(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py new file mode 100644 index 000000000000..881633c6d99a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_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 alloydb_v1beta + + +def sample_list_clusters(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_async.py new file mode 100644 index 000000000000..005a0696594b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1beta + + +async def sample_list_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_sync.py new file mode 100644 index 000000000000..e1800ab2c86b --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_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 alloydb_v1beta + + +def sample_list_instances(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_async.py new file mode 100644 index 000000000000..e8de1f550607 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1beta + + +async def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_sync.py new file mode 100644 index 000000000000..20d336e4cede --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportedDatabaseFlags +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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 alloydb_v1beta + + +def sample_list_supported_database_flags(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_supported_database_flags(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_async.py new file mode 100644 index 000000000000..b0ffd857e21e --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1beta + + +async def sample_list_users(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_sync.py new file mode 100644 index 000000000000..afb30dfa3b55 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_users_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_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 alloydb_v1beta + + +def sample_list_users(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_async.py new file mode 100644 index 000000000000..1975ba78acec --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1beta + + +async def sample_promote_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_sync.py new file mode 100644 index 000000000000..9552cbaff0c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_promote_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PromoteCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_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 alloydb_v1beta + + +def sample_promote_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.PromoteClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.promote_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_async.py new file mode 100644 index 000000000000..28e067af4aa7 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1beta + + +async def sample_restart_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_sync.py new file mode 100644 index 000000000000..4babdda8888c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restart_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_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 alloydb_v1beta + + +def sample_restart_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.RestartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.restart_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_async.py new file mode 100644 index 000000000000..b53c27f39fe4 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_async.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1beta + + +async def sample_restore_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup_source = alloydb_v1beta.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_sync.py new file mode 100644 index 000000000000..a8d4a3e95480 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_restore_cluster_sync.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_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 alloydb_v1beta + + +def sample_restore_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup_source = alloydb_v1beta.BackupSource() + backup_source.backup_name = "backup_name_value" + + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.RestoreClusterRequest( + backup_source=backup_source, + parent="parent_value", + cluster_id="cluster_id_value", + cluster=cluster, + ) + + # Make the request + operation = client.restore_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_async.py new file mode 100644 index 000000000000..5de98d3b472f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1beta + + +async def sample_update_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_sync.py new file mode 100644 index 000000000000..0c9df4b7644a --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_backup_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_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 alloydb_v1beta + + +def sample_update_backup(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + backup = alloydb_v1beta.Backup() + backup.cluster_name = "cluster_name_value" + + request = alloydb_v1beta.UpdateBackupRequest( + backup=backup, + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_async.py new file mode 100644 index 000000000000..4f620d136b45 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1beta + + +async def sample_update_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_sync.py new file mode 100644 index 000000000000..df2eb165e5e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_cluster_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_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 alloydb_v1beta + + +def sample_update_cluster(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + cluster = alloydb_v1beta.Cluster() + cluster.backup_source.backup_name = "backup_name_value" + cluster.network = "network_value" + + request = alloydb_v1beta.UpdateClusterRequest( + cluster=cluster, + ) + + # Make the request + operation = client.update_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_async.py new file mode 100644 index 000000000000..07999459aef9 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1beta + + +async def sample_update_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_sync.py new file mode 100644 index 000000000000..e5395bd411ae --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_instance_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_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 alloydb_v1beta + + +def sample_update_instance(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + instance = alloydb_v1beta.Instance() + instance.instance_type = "SECONDARY" + + request = alloydb_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_async.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_async.py new file mode 100644 index 000000000000..f422c775a7ea --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1beta + + +async def sample_update_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_async] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_sync.py b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_sync.py new file mode 100644 index 000000000000..41b98626913c --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_update_user_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_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 alloydb_v1beta + + +def sample_update_user(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_sync] diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json new file mode 100644 index 000000000000..aa82cb9c4be0 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json @@ -0,0 +1,5120 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.alloydb.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-alloydb", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.batch_create_instances", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.BatchCreateInstances", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "BatchCreateInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.BatchCreateInstancesRequest" + }, + { + "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": "batch_create_instances" + }, + "description": "Sample for BatchCreateInstances", + "file": "alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_BatchCreateInstances_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_batch_create_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1beta_generated_alloy_db_admin_create_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateBackup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateBackupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_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": "alloydb_v1beta_generated_alloy_db_admin_create_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateBackup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "name": "cluster_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_cluster" + }, + "description": "Sample for CreateCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "name": "instance_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_instance" + }, + "description": "Sample for CreateInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_secondary_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateSecondaryCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateSecondaryClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "name": "cluster_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_secondary_cluster" + }, + "description": "Sample for CreateSecondaryCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryCluster_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_secondary_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateSecondaryInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateSecondaryInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateSecondaryInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "name": "instance_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_secondary_instance" + }, + "description": "Sample for CreateSecondaryInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateSecondaryInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_secondary_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1beta.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1beta.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.create_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.CreateUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1beta.types.User" + }, + { + "name": "user_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1beta.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_CreateUser_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1beta_generated_alloy_db_admin_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.delete_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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": "alloydb_v1beta_generated_alloy_db_admin_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1beta_generated_alloy_db_admin_delete_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.delete_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for DeleteCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteCluster_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": "alloydb_v1beta_generated_alloy_db_admin_delete_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1beta_generated_alloy_db_admin_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.delete_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteInstanceRequest" + }, + { + "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_instance" + }, + "description": "Sample for DeleteInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteInstance_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": "alloydb_v1beta_generated_alloy_db_admin_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.delete_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.DeleteUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.DeleteUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_user" + }, + "description": "Sample for DeleteUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_DeleteUser_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_failover_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1beta_generated_alloy_db_admin_failover_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.failover_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.FailoverInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "FailoverInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.FailoverInstanceRequest" + }, + { + "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": "failover_instance" + }, + "description": "Sample for FailoverInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_failover_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_FailoverInstance_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": "alloydb_v1beta_generated_alloy_db_admin_failover_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GenerateClientCertificateRequest" + }, + { + "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.alloydb_v1beta.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_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": "alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GenerateClientCertificateRequest" + }, + { + "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.alloydb_v1beta.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GenerateClientCertificate_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": "alloydb_v1beta_generated_alloy_db_admin_generate_client_certificate_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.get_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetClusterRequest" + }, + { + "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.alloydb_v1beta.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1beta_generated_alloy_db_admin_get_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.get_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetClusterRequest" + }, + { + "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.alloydb_v1beta.types.Cluster", + "shortName": "get_cluster" + }, + "description": "Sample for GetCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetCluster_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": "alloydb_v1beta_generated_alloy_db_admin_get_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetConnectionInfoRequest" + }, + { + "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.alloydb_v1beta.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_connection_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_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": "alloydb_v1beta_generated_alloy_db_admin_get_connection_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetConnectionInfoRequest" + }, + { + "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.alloydb_v1beta.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_connection_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetConnectionInfo_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": "alloydb_v1beta_generated_alloy_db_admin_get_connection_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetInstanceRequest" + }, + { + "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.alloydb_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1beta_generated_alloy_db_admin_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.get_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetInstanceRequest" + }, + { + "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.alloydb_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetInstance_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": "alloydb_v1beta_generated_alloy_db_admin_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetUserRequest" + }, + { + "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.alloydb_v1beta.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1beta_generated_alloy_db_admin_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.get_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.GetUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.GetUserRequest" + }, + { + "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.alloydb_v1beta.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_GetUser_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": "alloydb_v1beta_generated_alloy_db_admin_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1beta.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1beta_generated_alloy_db_admin_inject_fault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1beta_generated_alloy_db_admin_inject_fault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.inject_fault", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.InjectFault", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "InjectFault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.InjectFaultRequest" + }, + { + "name": "fault_type", + "type": "google.cloud.alloydb_v1beta.types.InjectFaultRequest.FaultType" + }, + { + "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": "inject_fault" + }, + "description": "Sample for InjectFault", + "file": "alloydb_v1beta_generated_alloy_db_admin_inject_fault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_InjectFault_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": "alloydb_v1beta_generated_alloy_db_admin_inject_fault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1beta.services.alloy_db_admin.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_backups", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListBackups", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_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.alloydb_v1beta.services.alloy_db_admin.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_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": "alloydb_v1beta_generated_alloy_db_admin_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListClustersRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListClustersAsyncPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1beta_generated_alloy_db_admin_list_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_clusters", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListClusters", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListClustersRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListClustersPager", + "shortName": "list_clusters" + }, + "description": "Sample for ListClusters", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListClusters_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": "alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListInstancesRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1beta_generated_alloy_db_admin_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_instances", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListInstances", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListInstancesRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListInstances_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": "alloydb_v1beta_generated_alloy_db_admin_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsAsyncPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_supported_database_flags", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListSupportedDatabaseFlags", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListSupportedDatabaseFlags" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListSupportedDatabaseFlagsRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListSupportedDatabaseFlagsPager", + "shortName": "list_supported_database_flags" + }, + "description": "Sample for ListSupportedDatabaseFlags", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListSupportedDatabaseFlags_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": "alloydb_v1beta_generated_alloy_db_admin_list_supported_database_flags_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListUsersRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1beta_generated_alloy_db_admin_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_users", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListUsers", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListUsersRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListUsers_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": "alloydb_v1beta_generated_alloy_db_admin_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_promote_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1beta_generated_alloy_db_admin_promote_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.promote_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.PromoteCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "PromoteCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.PromoteClusterRequest" + }, + { + "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": "promote_cluster" + }, + "description": "Sample for PromoteCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_promote_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_PromoteCluster_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": "alloydb_v1beta_generated_alloy_db_admin_promote_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_restart_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1beta_generated_alloy_db_admin_restart_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.restart_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.RestartInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.RestartInstanceRequest" + }, + { + "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": "restart_instance" + }, + "description": "Sample for RestartInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_restart_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_RestartInstance_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": "alloydb_v1beta_generated_alloy_db_admin_restart_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_restore_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_restore_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.restore_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.RestoreCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "RestoreCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.RestoreClusterRequest" + }, + { + "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_cluster" + }, + "description": "Sample for RestoreCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_restore_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_RestoreCluster_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_restore_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1beta.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1beta_generated_alloy_db_admin_update_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.update_backup", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateBackup", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.alloydb_v1beta.types.Backup" + }, + { + "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_backup" + }, + "description": "Sample for UpdateBackup", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateBackup_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": "alloydb_v1beta_generated_alloy_db_admin_update_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_update_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.update_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateCluster", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateClusterRequest" + }, + { + "name": "cluster", + "type": "google.cloud.alloydb_v1beta.types.Cluster" + }, + { + "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_cluster" + }, + "description": "Sample for UpdateCluster", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateCluster_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_update_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1beta_generated_alloy_db_admin_update_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.update_instance", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateInstance", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.alloydb_v1beta.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateInstance_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": "alloydb_v1beta_generated_alloy_db_admin_update_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1beta.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1beta.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.update_user", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.UpdateUser", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.cloud.alloydb_v1beta.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1beta.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "alloydb_v1beta_generated_alloy_db_admin_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_UpdateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1beta_generated_alloy_db_admin_update_user_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/scripts/fixup_alloydb_v1beta_keywords.py b/owl-bot-staging/google-cloud-alloydb/v1beta/scripts/fixup_alloydb_v1beta_keywords.py new file mode 100644 index 000000000000..14b3ca7826ae --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/scripts/fixup_alloydb_v1beta_keywords.py @@ -0,0 +1,206 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class alloydbCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_instances': ('parent', 'requests', 'request_id', ), + 'create_backup': ('parent', 'backup_id', 'backup', 'request_id', 'validate_only', ), + 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_secondary_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', 'validate_only', ), + 'create_secondary_instance': ('parent', 'instance_id', 'instance', 'request_id', 'validate_only', ), + 'create_user': ('parent', 'user_id', 'user', 'request_id', 'validate_only', ), + 'delete_backup': ('name', 'request_id', 'validate_only', 'etag', ), + 'delete_cluster': ('name', 'request_id', 'etag', 'validate_only', 'force', ), + 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), + 'delete_user': ('name', 'request_id', 'validate_only', ), + 'failover_instance': ('name', 'request_id', 'validate_only', ), + 'generate_client_certificate': ('parent', 'request_id', 'pem_csr', 'cert_duration', 'public_key', 'use_metadata_exchange', ), + 'get_backup': ('name', ), + 'get_cluster': ('name', 'view', ), + 'get_connection_info': ('parent', 'request_id', ), + 'get_instance': ('name', 'view', ), + 'get_user': ('name', ), + 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), + 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_supported_database_flags': ('parent', 'page_size', 'page_token', ), + 'list_users': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'promote_cluster': ('name', 'request_id', 'etag', 'validate_only', ), + 'restart_instance': ('name', 'request_id', 'validate_only', ), + 'restore_cluster': ('parent', 'cluster_id', 'cluster', 'backup_source', 'continuous_backup_source', 'request_id', 'validate_only', ), + 'update_backup': ('backup', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_cluster': ('cluster', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_instance': ('instance', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + 'update_user': ('user', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), + } + + 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=alloydbCallTransformer(), +): + """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 alloydb client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/setup.py b/owl-bot-staging/google-cloud-alloydb/v1beta/setup.py new file mode 100644 index 000000000000..4c8aa9156a9f --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-alloydb' + + +description = "Google Cloud Alloydb API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/alloydb/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-alloydb" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2beecf99e0be --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-alloydb/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/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/google-cloud-alloydb/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/__init__.py b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py new file mode 100644 index 000000000000..8d5464090245 --- /dev/null +++ b/owl-bot-staging/google-cloud-alloydb/v1beta/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py @@ -0,0 +1,18468 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.alloydb_v1beta.services.alloy_db_admin import AlloyDBAdminAsyncClient +from google.cloud.alloydb_v1beta.services.alloy_db_admin import AlloyDBAdminClient +from google.cloud.alloydb_v1beta.services.alloy_db_admin import pagers +from google.cloud.alloydb_v1beta.services.alloy_db_admin import transports +from google.cloud.alloydb_v1beta.types import resources +from google.cloud.alloydb_v1beta.types import service +from google.cloud.location import locations_pb2 +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 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +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.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_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 AlloyDBAdminClient._get_default_mtls_endpoint(None) is None + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AlloyDBAdminClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AlloyDBAdminGrpcTransport, "grpc"), + (transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, "grpc"), + (AlloyDBAdminAsyncClient, "grpc_asyncio"), + (AlloyDBAdminClient, "rest"), +]) +def test_alloy_db_admin_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 == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://alloydb.googleapis.com' + ) + + +def test_alloy_db_admin_client_get_transport_class(): + transport = AlloyDBAdminClient.get_transport_class() + available_transports = [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminRestTransport, + ] + assert transport in available_transports + + transport = AlloyDBAdminClient.get_transport_class("grpc") + assert transport == transports.AlloyDBAdminGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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(AlloyDBAdminClient, '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(AlloyDBAdminClient, '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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "true"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", "false"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "true"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", "false"), +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_alloy_db_admin_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", [ + AlloyDBAdminClient, AlloyDBAdminAsyncClient +]) +@mock.patch.object(AlloyDBAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminClient)) +@mock.patch.object(AlloyDBAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AlloyDBAdminAsyncClient)) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), +]) +def test_alloy_db_admin_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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest", None), +]) +def test_alloy_db_admin_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_alloy_db_admin_client_client_options_from_dict(): + with mock.patch('google.cloud.alloydb_v1beta.services.alloy_db_admin.transports.AlloyDBAdminGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc", grpc_helpers), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_clusters), + '__call__') as call: + client.list_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + +@pytest.mark.asyncio +async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=service.ListClustersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_clusters_async_from_dict(): + await test_list_clusters_async(request_type=dict) + + +def test_list_clusters_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = service.ListClustersResponse() + client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_clusters_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + await client.list_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_clusters_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_clusters( + 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_clusters_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_clusters_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_clusters( + 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_clusters_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) +def test_list_clusters_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clusters(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_clusters_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clusters(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Cluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_clusters_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + ) + response = client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +def test_get_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.get_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + +@pytest.mark.asyncio +async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=service.GetClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + )) + response = await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +@pytest.mark.asyncio +async def test_get_cluster_async_from_dict(): + await test_get_cluster_async(request_type=dict) + + +def test_get_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = resources.Cluster() + client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + await client.get_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Cluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.create_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + +@pytest.mark.asyncio +async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_cluster_async_from_dict(): + await test_create_cluster_async(request_type=dict) + + +def test_create_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_cluster), + '__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_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.update_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + +@pytest.mark.asyncio +async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_cluster_async_from_dict(): + await test_update_cluster_async(request_type=dict) + + +def test_update_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateClusterRequest() + + request.cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_cluster), + '__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_cluster( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.delete_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + +@pytest.mark.asyncio +async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_cluster_async_from_dict(): + await test_delete_cluster_async(request_type=dict) + + +def test_delete_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_cluster), + '__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_cluster( + 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_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_promote_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + client.promote_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + +@pytest.mark.asyncio +async def test_promote_cluster_async(transport: str = 'grpc_asyncio', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.PromoteClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_promote_cluster_async_from_dict(): + await test_promote_cluster_async(request_type=dict) + + +def test_promote_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_promote_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.PromoteClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_promote_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_promote_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.promote_cluster), + '__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.promote_cluster( + 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_promote_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_cluster), + '__call__') as call: + client.restore_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + +@pytest.mark.asyncio +async def test_restore_cluster_async(transport: str = 'grpc_asyncio', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_cluster), + '__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_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_cluster_async_from_dict(): + await test_restore_cluster_async(request_type=dict) + + +def test_restore_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_restore_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_cluster), + '__call__') as call: + client.create_secondary_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_cluster), + '__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_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_cluster_async_from_dict(): + await test_create_secondary_cluster_async(request_type=dict) + + +def test_create_secondary_cluster_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_cluster_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_cluster_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + + +def test_create_secondary_cluster_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_cluster), + '__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_secondary_cluster( + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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].cluster + mock_val = resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = 'cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instances), + '__call__') as call: + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=service.ListInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = service.ListInstancesResponse() + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instances_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + 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_instances_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListInstancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + 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_instances_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) +def test_list_instances_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Instance) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +def test_get_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=service.GetInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = resources.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.create_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + +@pytest.mark.asyncio +async def test_create_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__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_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_secondary_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_secondary_instance), + '__call__') as call: + client.create_secondary_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + +@pytest.mark.asyncio +async def test_create_secondary_instance_async(transport: str = 'grpc_asyncio', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_secondary_instance), + '__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_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateSecondaryInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_secondary_instance_async_from_dict(): + await test_create_secondary_instance_async(request_type=dict) + + +def test_create_secondary_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_secondary_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecondaryInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_secondary_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_secondary_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_secondary_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_secondary_instance), + '__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_secondary_instance( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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].instance + mock_val = resources.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_secondary_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_create_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + client.batch_create_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + +@pytest.mark.asyncio +async def test_batch_create_instances_async(transport: str = 'grpc_asyncio', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__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.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.BatchCreateInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_create_instances_async_from_dict(): + await test_batch_create_instances_async(request_type=dict) + + +def test_batch_create_instances_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchCreateInstancesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_create_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.update_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + +@pytest.mark.asyncio +async def test_update_instance_async(transport: str = 'grpc_asyncio', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_instance_async_from_dict(): + await test_update_instance_async(request_type=dict) + + +def test_update_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateInstanceRequest() + + request.instance.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'instance.name=name_value', + ) in kw['metadata'] + + +def test_update_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_instance), + '__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_instance( + instance=resources.Instance(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].instance + mock_val = resources.Instance(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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_instance), + '__call__') as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + +@pytest.mark.asyncio +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), + '__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__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_instance( + 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_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_failover_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + client.failover_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + +@pytest.mark.asyncio +async def test_failover_instance_async(transport: str = 'grpc_asyncio', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.FailoverInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_failover_instance_async_from_dict(): + await test_failover_instance_async(request_type=dict) + + +def test_failover_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_failover_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.FailoverInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_failover_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_failover_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), + '__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.failover_instance( + 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_failover_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_inject_fault_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + client.inject_fault() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + +@pytest.mark.asyncio +async def test_inject_fault_async(transport: str = 'grpc_asyncio', request_type=service.InjectFaultRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.InjectFaultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_inject_fault_async_from_dict(): + await test_inject_fault_async(request_type=dict) + + +def test_inject_fault_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_inject_fault_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.InjectFaultRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.inject_fault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_inject_fault_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_inject_fault_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + +@pytest.mark.asyncio +async def test_inject_fault_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.inject_fault), + '__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.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_inject_fault_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restart_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + client.restart_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + +@pytest.mark.asyncio +async def test_restart_instance_async(transport: str = 'grpc_asyncio', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestartInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restart_instance_async_from_dict(): + await test_restart_instance_async(request_type=dict) + + +def test_restart_instance_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_restart_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestartInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_restart_instance_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_restart_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_instance), + '__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.restart_instance( + 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_restart_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = service.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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.ListBackupsRequest() + +@pytest.mark.asyncio +async def test_list_backups_async(transport: str = 'grpc_asyncio', request_type=service.ListBackupsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(service.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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(service.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 = AlloyDBAdminClient( + 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 = service.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 = AlloyDBAdminClient( + credentials=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( + service.ListBackupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = service.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in results) +def test_list_backups_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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 = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.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, resources.Backup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = AlloyDBAdminAsyncClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_backups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +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 = AlloyDBAdminClient( + credentials=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] == service.GetBackupRequest() + +@pytest.mark.asyncio +async def test_get_backup_async(transport: str = 'grpc_asyncio', request_type=service.GetBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + )) + 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] == service.GetBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +@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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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(resources.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 = AlloyDBAdminClient( + 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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.GetBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = resources.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.GetBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.CreateBackupRequest() + +@pytest.mark.asyncio +async def test_create_backup_async(transport: str = 'grpc_asyncio', request_type=service.CreateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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=resources.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 = resources.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 = AlloyDBAdminClient( + credentials=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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + +@pytest.mark.asyncio +async def test_create_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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=resources.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 = resources.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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_backup), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_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] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_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 = AlloyDBAdminClient( + credentials=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_backup), + '__call__') as call: + client.update_backup() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + +@pytest.mark.asyncio +async def test_update_backup_async(transport: str = 'grpc_asyncio', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateBackupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_backup_async_from_dict(): + await test_update_backup_async(request_type=dict) + + +def test_update_backup_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_backup_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateBackupRequest() + + request.backup.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_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', + 'backup.name=name_value', + ) in kw['metadata'] + + +def test_update_backup_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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.update_backup( + backup=resources.Backup(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].backup + mock_val = resources.Backup(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_backup_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=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] == service.DeleteBackupRequest() + +@pytest.mark.asyncio +async def test_delete_backup_async(transport: str = 'grpc_asyncio', request_type=service.DeleteBackupRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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] == service.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=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( + service.DeleteBackupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_supported_database_flags), + '__call__') as call: + client.list_supported_database_flags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async(transport: str = 'grpc_asyncio', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListSupportedDatabaseFlagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_from_dict(): + await test_list_supported_database_flags_async(request_type=dict) + + +def test_list_supported_database_flags_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = service.ListSupportedDatabaseFlagsResponse() + client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_supported_database_flags_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSupportedDatabaseFlagsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + await client.list_supported_database_flags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_supported_database_flags_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_supported_database_flags( + 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_supported_database_flags_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_supported_database_flags_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListSupportedDatabaseFlagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_supported_database_flags( + 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_supported_database_flags_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_supported_database_flags(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) +def test_list_supported_database_flags_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_supported_database_flags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_supported_database_flags(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_supported_database_flags_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_supported_database_flags(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_supported_database_flags(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GenerateClientCertificateRequest, + dict, +]) +def test_generate_client_certificate(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + ) + response = client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +def test_generate_client_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + client.generate_client_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + +@pytest.mark.asyncio +async def test_generate_client_certificate_async(transport: str = 'grpc_asyncio', request_type=service.GenerateClientCertificateRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + )) + response = await client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateClientCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +@pytest.mark.asyncio +async def test_generate_client_certificate_async_from_dict(): + await test_generate_client_certificate_async(request_type=dict) + + +def test_generate_client_certificate_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateClientCertificateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + call.return_value = service.GenerateClientCertificateResponse() + client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_generate_client_certificate_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateClientCertificateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse()) + await client.generate_client_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_generate_client_certificate_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_client_certificate( + 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_generate_client_certificate_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_generate_client_certificate_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_client_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateClientCertificateResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateClientCertificateResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_client_certificate( + 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_generate_client_certificate_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetConnectionInfoRequest, + dict, +]) +def test_get_connection_info(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + ) + response = client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +def test_get_connection_info_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_connection_info), + '__call__') as call: + client.get_connection_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + +@pytest.mark.asyncio +async def test_get_connection_info_async(transport: str = 'grpc_asyncio', request_type=service.GetConnectionInfoRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + )) + response = await client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +@pytest.mark.asyncio +async def test_get_connection_info_async_from_dict(): + await test_get_connection_info_async(request_type=dict) + + +def test_get_connection_info_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + call.return_value = resources.ConnectionInfo() + client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_connection_info_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo()) + await client.get_connection_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_connection_info_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_connection_info( + 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_get_connection_info_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_get_connection_info_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConnectionInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_connection_info( + 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_get_connection_info_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListUsersRequest, + dict, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_users), + '__call__') as call: + client.list_users() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + +@pytest.mark.asyncio +async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=service.ListUsersRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListUsersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) + + +def test_list_users_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = service.ListUsersResponse() + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_users_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_users_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + 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_users_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListUsersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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_users_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_users(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetUserRequest, + dict, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.get_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + +@pytest.mark.asyncio +async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=service.GetUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + + +def test_get_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = resources.User() + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.create_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + +@pytest.mark.asyncio +async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=service.CreateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) + + +def test_create_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = resources.User() + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_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].user + mock_val = resources.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.update_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + +@pytest.mark.asyncio +async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=service.UpdateUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + + +def test_update_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = resources.User() + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'user.name=name_value', + ) in kw['metadata'] + + +def test_update_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=resources.User(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].user + mock_val = resources.User(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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=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_user), + '__call__') as call: + client.delete_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + +@pytest.mark.asyncio +async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=service.DeleteUserRequest): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + + +def test_delete_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user( + 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_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=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_user( + service.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user( + 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_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListClustersRequest, + dict, +]) +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListClustersResponse( + 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 = service.ListClustersResponse.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_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_clusters._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_clusters._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListClustersResponse.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_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_clusters._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_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_clusters") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json(service.ListClustersResponse()) + + request = service.ListClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request(transport: str = 'rest', request_type=service.ListClustersRequest): + client = AlloyDBAdminClient( + 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_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + + # 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 = service.ListClustersResponse.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_clusters(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_list_clusters_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_clusters( + service.ListClustersRequest(), + parent='parent_value', + ) + + +def test_list_clusters_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token='abc', + ), + service.ListClustersResponse( + clusters=[], + next_page_token='def', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token='ghi', + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.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_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) + for i in results) + + pages = list(client.list_clusters(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", [ + service.GetClusterRequest, + dict, +]) +def test_get_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network='network_value', + etag='etag_value', + reconciling=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.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_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == 'network_value' + assert response.etag == 'etag_value' + assert response.reconciling is True + + +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Cluster.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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + + request = service.GetClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Cluster() + + client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request(transport: str = 'rest', request_type=service.GetClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/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 = resources.Cluster.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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_get_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.GetClusterRequest(), + name='name_value', + ) + + +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateClusterRequest, + dict, +]) +def test_create_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_cluster(request) + + +def test_create_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters" % client.transport._host, args[1]) + + +def test_create_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.CreateClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateClusterRequest, + dict, +]) +def test_update_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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.update_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_cluster_rest_bad_request(transport: str = 'rest', request_type=service.UpdateClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'projects/sample1/locations/sample2/clusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_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_cluster(**mock_args) + + # Establish that the underlying call 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/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) + + +def test_update_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteClusterRequest, + dict, +]) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_cluster._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_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request(transport: str = 'rest', request_type=service.DeleteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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_cluster(request) + + +def test_delete_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}" % client.transport._host, args[1]) + + +def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_cluster( + service.DeleteClusterRequest(), + name='name_value', + ) + + +def test_delete_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.PromoteClusterRequest, + dict, +]) +def test_promote_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_promote_cluster_rest_required_fields(request_type=service.PromoteClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).promote_cluster._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()).promote_cluster._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 = AlloyDBAdminClient( + 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.promote_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_promote_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_promote_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_promote_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.PromoteClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.promote_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_promote_cluster_rest_bad_request(transport: str = 'rest', request_type=service.PromoteClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/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.promote_cluster(request) + + +def test_promote_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/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.promote_cluster(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}:promote" % client.transport._host, args[1]) + + +def test_promote_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.promote_cluster( + service.PromoteClusterRequest(), + name='name_value', + ) + + +def test_promote_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreClusterRequest, + dict, +]) +def test_restore_cluster_rest(request_type): + client = AlloyDBAdminClient( + 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 = 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_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_cluster_rest_required_fields(request_type=service.RestoreClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restore_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestoreClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_cluster_rest_bad_request(transport: str = 'rest', request_type=service.RestoreClusterRequest): + client = AlloyDBAdminClient( + 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.restore_cluster(request) + + +def test_restore_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryClusterRequest, + dict, +]) +def test_create_secondary_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_secondary_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_cluster_rest_required_fields(request_type=service.CreateSecondaryClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_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 "clusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clusterId"] = 'cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cluster_id", "request_id", "validate_only", )) + 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 "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == 'cluster_id_value' + + client = AlloyDBAdminClient( + 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_secondary_cluster(request) + + expected_params = [ + ( + "clusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clusterId", "requestId", "validateOnly", )) & set(("parent", "clusterId", "cluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryClusterRequest.pb(service.CreateSecondaryClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_cluster_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryClusterRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["cluster"] = {'backup_source': {'backup_uid': 'backup_uid_value', 'backup_name': 'backup_name_value'}, 'migration_source': {'host_port': 'host_port_value', 'reference_id': 'reference_id_value', 'source_type': 1}, 'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'cluster_type': 1, 'database_version': 1, 'network_config': {'network': 'network_value', 'allocated_ip_range': 'allocated_ip_range_value'}, 'network': 'network_value', 'etag': 'etag_value', 'annotations': {}, 'reconciling': True, 'initial_user': {'user': 'user_value', 'password': 'password_value'}, 'automated_backup_policy': {'weekly_schedule': {'start_times': [{'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}], 'days_of_week': [1]}, 'time_based_retention': {'retention_period': {'seconds': 751, 'nanos': 543}}, 'quantity_based_retention': {'count': 553}, 'enabled': True, 'backup_window': {}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'location': 'location_value', 'labels': {}}, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}, 'encryption_config': {}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'continuous_backup_config': {'enabled': True, 'recovery_window_days': 2166, 'encryption_config': {}}, 'continuous_backup_info': {'encryption_info': {}, 'enabled_time': {}, 'schedule': [1], 'earliest_restorable_time': {}}, 'secondary_config': {'primary_cluster_name': 'primary_cluster_name_value'}, 'primary_config': {'secondary_cluster_names': ['secondary_cluster_names_value1', 'secondary_cluster_names_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_secondary_cluster(request) + + +def test_create_secondary_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_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_secondary_cluster(**mock_args) + + # Establish that the underlying call 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/*}/clusters:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_cluster_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent='parent_value', + cluster=resources.Cluster(backup_source=resources.BackupSource(backup_uid='backup_uid_value')), + cluster_id='cluster_id_value', + ) + + +def test_create_secondary_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListInstancesRequest, + dict, +]) +def test_list_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse( + 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 = service.ListInstancesResponse.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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instances._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_instances._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListInstancesResponse.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_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_instances._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_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListInstancesResponse.to_json(service.ListInstancesResponse()) + + request = service.ListInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListInstancesResponse() + + client.list_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request(transport: str = 'rest', request_type=service.ListInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_instances(request) + + +def test_list_instances_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListInstancesResponse.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_instances(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_list_instances_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instances( + service.ListInstancesRequest(), + parent='parent_value', + ) + + +def test_list_instances_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token='abc', + ), + service.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token='ghi', + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.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/clusters/sample3'} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) + for i in results) + + pages = list(client.list_instances(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", [ + service.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone='gce_zone_value', + ip_address='ip_address_value', + reconciling=True, + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Instance.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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Instance) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == 'gce_zone_value' + assert response.ip_address == 'ip_address_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + + +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.Instance.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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Instance.to_json(resources.Instance()) + + request = service.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=service.GetInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_get_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.Instance.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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateInstanceRequest, + dict, +]) +def test_create_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_instance_rest_required_fields(request_type=service.CreateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + +def test_create_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances" % client.transport._host, args[1]) + + +def test_create_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.CreateInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateSecondaryInstanceRequest, + dict, +]) +def test_create_secondary_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_secondary_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_secondary_instance_rest_required_fields(request_type=service.CreateSecondaryInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_secondary_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", "request_id", "validate_only", )) + 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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = AlloyDBAdminClient( + 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_secondary_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_secondary_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", "requestId", "validateOnly", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_secondary_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_secondary_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateSecondaryInstanceRequest.pb(service.CreateSecondaryInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.CreateSecondaryInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_secondary_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_secondary_instance_rest_bad_request(transport: str = 'rest', request_type=service.CreateSecondaryInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["instance"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_secondary_instance(request) + + +def test_create_secondary_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_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_secondary_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1]) + + +def test_create_secondary_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent='parent_value', + instance=resources.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_secondary_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.BatchCreateInstancesRequest, + dict, +]) +def test_batch_create_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}}}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and 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.batch_create_instances(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_create_instances_rest_required_fields(request_type=service.BatchCreateInstancesRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).batch_create_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + 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.batch_create_instances(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_instances_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_instances_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_batch_create_instances") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.BatchCreateInstancesRequest.pb(service.BatchCreateInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.BatchCreateInstancesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_create_instances(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_instances_rest_bad_request(transport: str = 'rest', request_type=service.BatchCreateInstancesRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["requests"] = {'create_instance_requests': [{'parent': 'parent_value', 'instance_id': 'instance_id_value', 'instance': {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 1}}}, 'request_id': 'request_id_value', 'validate_only': True}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_instances(request) + + +def test_batch_create_instances_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateInstanceRequest, + dict, +]) +def test_update_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_instance_rest_required_fields(request_type=service.UpdateInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request(transport: str = 'rest', request_type=service.UpdateInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + request_init["instance"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'instance_type': 1, 'machine_config': {'cpu_count': 976}, 'availability_type': 1, 'gce_zone': 'gce_zone_value', 'database_flags': {}, 'writable_node': {'zone_id': 'zone_id_value', 'id': 'id_value', 'ip': 'ip_value', 'state': 'state_value'}, 'nodes': {}, 'query_insights_config': {'record_application_tags': True, 'record_client_address': True, 'query_string_length': 2061, 'query_plans_per_minute': 2378}, 'read_pool_config': {'node_count': 1070}, 'ip_address': 'ip_address_value', 'reconciling': True, 'etag': 'etag_value', 'annotations': {}, 'update_policy': {'mode': 1}, 'client_connection_config': {'require_connectors': True, 'ssl_config': {'ssl_mode': 1, 'ca_source': 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_instance(request) + + +def test_update_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'instance': {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + instance=resources.Instance(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_instance(**mock_args) + + # Establish that the underlying call 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/{instance.name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_update_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_instance_rest_required_fields(request_type=service.DeleteInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.DeleteInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request(transport: str = 'rest', request_type=service.DeleteInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_instance(request) + + +def test_delete_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}" % client.transport._host, args[1]) + + +def test_delete_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_instance( + service.DeleteInstanceRequest(), + name='name_value', + ) + + +def test_delete_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.FailoverInstanceRequest, + dict, +]) +def test_failover_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_failover_instance_rest_required_fields(request_type=service.FailoverInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).failover_instance._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()).failover_instance._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 = AlloyDBAdminClient( + 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.failover_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_failover_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_failover_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_failover_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_failover_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FailoverInstanceRequest.pb(service.FailoverInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.FailoverInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.failover_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_failover_instance_rest_bad_request(transport: str = 'rest', request_type=service.FailoverInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.failover_instance(request) + + +def test_failover_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.failover_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:failover" % client.transport._host, args[1]) + + +def test_failover_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_instance( + service.FailoverInstanceRequest(), + name='name_value', + ) + + +def test_failover_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.InjectFaultRequest, + dict, +]) +def test_inject_fault_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).inject_fault._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()).inject_fault._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 = AlloyDBAdminClient( + 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.inject_fault(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_inject_fault_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.inject_fault._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("faultType", "name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_inject_fault_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_inject_fault") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_inject_fault") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.InjectFaultRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.inject_fault(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_inject_fault_rest_bad_request(transport: str = 'rest', request_type=service.InjectFaultRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.inject_fault(request) + + +def test_inject_fault_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + 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.inject_fault(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1]) + + +def test_inject_fault_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name='name_value', + ) + + +def test_inject_fault_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestartInstanceRequest, + dict, +]) +def test_restart_instance_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restart_instance_rest_required_fields(request_type=service.RestartInstanceRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).restart_instance._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()).restart_instance._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 = AlloyDBAdminClient( + 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.restart_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restart_instance_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restart_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restart_instance_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_restart_instance") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_restart_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.RestartInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restart_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restart_instance_rest_bad_request(transport: str = 'rest', request_type=service.RestartInstanceRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/instances/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.restart_instance(request) + + +def test_restart_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/clusters/sample3/instances/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.restart_instance(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}:restart" % client.transport._host, args[1]) + + +def test_restart_instance_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restart_instance( + service.RestartInstanceRequest(), + name='name_value', + ) + + +def test_restart_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListBackupsRequest, + dict, +]) +def test_list_backups_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.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 = service.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=service.ListBackupsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.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 = service.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_backups") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_backups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListBackupsRequest.pb(service.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 = service.ListBackupsResponse.to_json(service.ListBackupsResponse()) + + request = service.ListBackupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.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=service.ListBackupsRequest): + client = AlloyDBAdminClient( + 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_backups(request) + + +def test_list_backups_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListBackupsResponse() + + # 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 = service.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/*}/backups" % client.transport._host, args[1]) + + +def test_list_backups_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.ListBackupsRequest(), + parent='parent_value', + ) + + +def test_list_backups_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token='abc', + ), + service.ListBackupsResponse( + backups=[], + next_page_token='def', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token='ghi', + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.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'} + + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.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", [ + service.GetBackupRequest, + dict, +]) +def test_get_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup( + name='name_value', + display_name='display_name_value', + uid='uid_value', + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description='description_value', + cluster_uid='cluster_uid_value', + cluster_name='cluster_name_value', + reconciling=True, + etag='etag_value', + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.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, resources.Backup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == 'description_value' + assert response.cluster_uid == 'cluster_uid_value' + assert response.cluster_name == 'cluster_name_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + + +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.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 = resources.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.AlloyDBAdminRestTransport(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.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetBackupRequest.pb(service.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 = resources.Backup.to_json(resources.Backup()) + + request = service.GetBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.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=service.GetBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_get_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/backups/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 = resources.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/*/backups/*}" % client.transport._host, args[1]) + + +def test_get_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.GetBackupRequest(), + name='name_value', + ) + + +def test_get_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateBackupRequest, + dict, +]) +def test_create_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_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=service.CreateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("backupId", "requestId", "validateOnly", )) & set(("parent", "backupId", "backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_create_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateBackupRequest.pb(service.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 = service.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=service.CreateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["backup"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + +def test_create_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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', + backup=resources.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/*}/backups" % client.transport._host, args[1]) + + +def test_create_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.CreateBackupRequest(), + parent='parent_value', + backup=resources.Backup(name='name_value'), + backup_id='backup_id_value', + ) + + +def test_create_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateBackupRequest, + dict, +]) +def test_update_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_backup._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_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + 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_backup(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_backup_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("backup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_update_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = service.UpdateBackupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_backup(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_backup_rest_bad_request(transport: str = 'rest', request_type=service.UpdateBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + request_init["backup"] = {'name': 'projects/sample1/locations/sample2/backups/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'labels': {}, 'state': 1, 'type_': 1, 'description': 'description_value', 'cluster_uid': 'cluster_uid_value', 'cluster_name': 'cluster_name_value', 'reconciling': True, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'encryption_info': {'encryption_type': 1, 'kms_key_versions': ['kms_key_versions_value1', 'kms_key_versions_value2']}, 'etag': 'etag_value', 'annotations': {}, 'size_bytes': 1089, 'expiry_time': {}, 'expiry_quantity': {'retention_count': 1632, 'total_retention_count': 2275}, 'database_version': 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_backup(request) + + +def test_update_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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 = {'backup': {'name': 'projects/sample1/locations/sample2/backups/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + backup=resources.Backup(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_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/{backup.name=projects/*/locations/*/backups/*}" % client.transport._host, args[1]) + + +def test_update_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteBackupRequest, + dict, +]) +def test_delete_backup_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_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=service.DeleteBackupRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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(("etag", "request_id", "validate_only", )) + 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 = AlloyDBAdminClient( + 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.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_delete_backup") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_backup") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteBackupRequest.pb(service.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 = service.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=service.DeleteBackupRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/backups/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_backup(request) + + +def test_delete_backup_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/backups/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_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/*/backups/*}" % client.transport._host, args[1]) + + +def test_delete_backup_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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( + service.DeleteBackupRequest(), + name='name_value', + ) + + +def test_delete_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListSupportedDatabaseFlagsRequest, + dict, +]) +def test_list_supported_database_flags_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListSupportedDatabaseFlagsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_supported_database_flags_rest_required_fields(request_type=service.ListSupportedDatabaseFlagsRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_supported_database_flags._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_supported_database_flags._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_supported_database_flags_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_supported_database_flags._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_supported_database_flags_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListSupportedDatabaseFlagsRequest.pb(service.ListSupportedDatabaseFlagsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json(service.ListSupportedDatabaseFlagsResponse()) + + request = service.ListSupportedDatabaseFlagsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListSupportedDatabaseFlagsResponse() + + client.list_supported_database_flags(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_supported_database_flags_rest_bad_request(transport: str = 'rest', request_type=service.ListSupportedDatabaseFlagsRequest): + client = AlloyDBAdminClient( + 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_supported_database_flags(request) + + +def test_list_supported_database_flags_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListSupportedDatabaseFlagsResponse() + + # 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 = service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(**mock_args) + + # Establish that the underlying call 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/*}/supportedDatabaseFlags" % client.transport._host, args[1]) + + +def test_list_supported_database_flags_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent='parent_value', + ) + + +def test_list_supported_database_flags_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token='abc', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token='def', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token='ghi', + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) + for i in results) + + pages = list(client.list_supported_database_flags(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", [ + service.GenerateClientCertificateRequest, + dict, +]) +def test_generate_client_certificate_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.GenerateClientCertificateResponse( + pem_certificate='pem_certificate_value', + pem_certificate_chain=['pem_certificate_chain_value'], + ca_cert='ca_cert_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.GenerateClientCertificateResponse.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.generate_client_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == 'pem_certificate_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.ca_cert == 'ca_cert_value' + + +def test_generate_client_certificate_rest_required_fields(request_type=service.GenerateClientCertificateRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).generate_client_certificate._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()).generate_client_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateClientCertificateResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.GenerateClientCertificateResponse.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.generate_client_certificate(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_client_certificate_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_client_certificate_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateClientCertificateRequest.pb(service.GenerateClientCertificateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.GenerateClientCertificateResponse.to_json(service.GenerateClientCertificateResponse()) + + request = service.GenerateClientCertificateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateClientCertificateResponse() + + client.generate_client_certificate(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_client_certificate_rest_bad_request(transport: str = 'rest', request_type=service.GenerateClientCertificateRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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.generate_client_certificate(request) + + +def test_generate_client_certificate_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateClientCertificateResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.GenerateClientCertificateResponse.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.generate_client_certificate(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}:generateClientCertificate" % client.transport._host, args[1]) + + +def test_generate_client_certificate_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent='parent_value', + ) + + +def test_generate_client_certificate_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetConnectionInfoRequest, + dict, +]) +def test_get_connection_info_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/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 = resources.ConnectionInfo( + name='name_value', + ip_address='ip_address_value', + pem_certificate_chain=['pem_certificate_chain_value'], + instance_uid='instance_uid_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ConnectionInfo.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_connection_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == 'name_value' + assert response.ip_address == 'ip_address_value' + assert response.pem_certificate_chain == ['pem_certificate_chain_value'] + assert response.instance_uid == 'instance_uid_value' + + +def test_get_connection_info_rest_required_fields(request_type=service.GetConnectionInfoRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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()).get_connection_info._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()).get_connection_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConnectionInfo() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.ConnectionInfo.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_connection_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_connection_info_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_connection_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connection_info_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_connection_info") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetConnectionInfoRequest.pb(service.GetConnectionInfoRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.ConnectionInfo.to_json(resources.ConnectionInfo()) + + request = service.GetConnectionInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConnectionInfo() + + client.get_connection_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_connection_info_rest_bad_request(transport: str = 'rest', request_type=service.GetConnectionInfoRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/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_connection_info(request) + + +def test_get_connection_info_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConnectionInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3/instances/sample4'} + + # 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 = resources.ConnectionInfo.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_connection_info(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/instances/*}/connectionInfo" % client.transport._host, args[1]) + + +def test_get_connection_info_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_connection_info( + service.GetConnectionInfoRequest(), + parent='parent_value', + ) + + +def test_get_connection_info_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListUsersRequest, + dict, +]) +def test_list_users_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse( + 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 = service.ListUsersResponse.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_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_users._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_users._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = service.ListUsersResponse.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_users(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_users_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_users._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_users_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListUsersRequest.pb(service.ListUsersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListUsersResponse.to_json(service.ListUsersResponse()) + + request = service.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListUsersResponse() + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_users_rest_bad_request(transport: str = 'rest', request_type=service.ListUsersRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/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_users(request) + + +def test_list_users_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/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 = service.ListUsersResponse.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_users(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_list_users_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_users( + service.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_rest_pager(transport: str = 'rest'): + client = AlloyDBAdminClient( + 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 = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token='abc', + ), + service.ListUsersResponse( + users=[], + next_page_token='def', + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token='ghi', + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListUsersResponse.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/clusters/sample3'} + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) + for i in results) + + pages = list(client.list_users(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", [ + service.GetUserRequest, + dict, +]) +def test_get_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.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_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_get_user_rest_required_fields(request_type=service.GetUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.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_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetUserRequest.pb(service.GetUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_rest_bad_request(transport: str = 'rest', request_type=service.GetUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_get_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = resources.User.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_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.GetUserRequest(), + name='name_value', + ) + + +def test_get_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateUserRequest, + dict, +]) +def test_create_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_create_user_rest_required_fields(request_type=service.CreateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_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 "userId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userId"] = 'user_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._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", "user_id", "validate_only", )) + 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 "userId" in jsonified_request + assert jsonified_request["userId"] == 'user_id_value' + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_user(request) + + expected_params = [ + ( + "userId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "userId", "validateOnly", )) & set(("parent", "userId", "user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateUserRequest.pb(service.CreateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_rest_bad_request(transport: str = 'rest', request_type=service.CreateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + request_init["user"] = {'name': 'name_value', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_create_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_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 = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*}/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.CreateUserRequest(), + parent='parent_value', + user=resources.User(name='name_value'), + user_id='user_id_value', + ) + + +def test_create_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateUserRequest, + dict, +]) +def test_update_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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 = resources.User( + name='name_value', + password='password_value', + database_roles=['database_roles_value'], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == 'name_value' + assert response.password == 'password_value' + assert response.database_roles == ['database_roles_value'] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "request_id", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.User() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "requestId", "updateMask", "validateOnly", )) & set(("user", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateUserRequest.pb(service.UpdateUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.User.to_json(resources.User()) + + request = service.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.User() + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_rest_bad_request(transport: str = 'rest', request_type=service.UpdateUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + request_init["user"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4', 'password': 'password_value', 'database_roles': ['database_roles_value1', 'database_roles_value2'], 'user_type': 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_user(request) + + +def test_update_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'user': {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_user(**mock_args) + + # Establish that the underlying call 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/{user.name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_update_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.UpdateUserRequest(), + user=resources.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteUserRequest, + dict, +]) +def test_delete_user_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = 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_user(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_user._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_user._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", "validate_only", )) + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AlloyDBAdminRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = service.DeleteUserRequest.pb(service.DeleteUserRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = service.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_user_rest_bad_request(transport: str = 'rest', request_type=service.DeleteUserRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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_user(request) + + +def test_delete_user_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/users/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_user(**mock_args) + + # Establish that the underlying call 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/*/clusters/*/users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = AlloyDBAdminClient( + credentials=ga_credentials.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_user( + service.DeleteUserRequest(), + name='name_value', + ) + + +def test_delete_user_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AlloyDBAdminClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AlloyDBAdminClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AlloyDBAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, +]) +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 = AlloyDBAdminClient.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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AlloyDBAdminGrpcTransport, + ) + +def test_alloy_db_admin_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_alloy_db_admin_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.alloydb_v1beta.services.alloy_db_admin.transports.AlloyDBAdminTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AlloyDBAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_clusters', + 'get_cluster', + 'create_cluster', + 'update_cluster', + 'delete_cluster', + 'promote_cluster', + 'restore_cluster', + 'create_secondary_cluster', + 'list_instances', + 'get_instance', + 'create_instance', + 'create_secondary_instance', + 'batch_create_instances', + 'update_instance', + 'delete_instance', + 'failover_instance', + 'inject_fault', + 'restart_instance', + 'list_backups', + 'get_backup', + 'create_backup', + 'update_backup', + 'delete_backup', + 'list_supported_database_flags', + 'generate_client_certificate', + 'get_connection_info', + 'list_users', + 'get_user', + 'create_user', + 'update_user', + 'delete_user', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # 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_alloy_db_admin_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.alloydb_v1beta.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport( + 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_alloy_db_admin_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.alloydb_v1beta.services.alloy_db_admin.transports.AlloyDBAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AlloyDBAdminTransport() + adc.assert_called_once() + + +def test_alloy_db_admin_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) + AlloyDBAdminClient() + 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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, + transports.AlloyDBAdminGrpcAsyncIOTransport, + transports.AlloyDBAdminRestTransport, + ], +) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, grpc_helpers), + (transports.AlloyDBAdminGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_alloy_db_admin_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( + "alloydb.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="alloydb.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_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.AlloyDBAdminRestTransport ( + 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_alloy_db_admin_rest_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_host_no_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_alloy_db_admin_host_with_port(transport_name): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='alloydb.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'alloydb.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://alloydb.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_alloy_db_admin_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AlloyDBAdminClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AlloyDBAdminClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.promote_cluster._session + session2 = client2.transport.promote_cluster._session + assert session1 != session2 + session1 = client1.transport.restore_cluster._session + session2 = client2.transport.restore_cluster._session + assert session1 != session2 + session1 = client1.transport.create_secondary_cluster._session + session2 = client2.transport.create_secondary_cluster._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.create_secondary_instance._session + session2 = client2.transport.create_secondary_instance._session + assert session1 != session2 + session1 = client1.transport.batch_create_instances._session + session2 = client2.transport.batch_create_instances._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.failover_instance._session + session2 = client2.transport.failover_instance._session + assert session1 != session2 + session1 = client1.transport.inject_fault._session + session2 = client2.transport.inject_fault._session + assert session1 != session2 + session1 = client1.transport.restart_instance._session + session2 = client2.transport.restart_instance._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.update_backup._session + session2 = client2.transport.update_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.list_supported_database_flags._session + session2 = client2.transport.list_supported_database_flags._session + assert session1 != session2 + session1 = client1.transport.generate_client_certificate._session + session2 = client2.transport.generate_client_certificate._session + assert session1 != session2 + session1 = client1.transport.get_connection_info._session + session2 = client2.transport.get_connection_info._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 +def test_alloy_db_admin_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcTransport( + 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_alloy_db_admin_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AlloyDBAdminGrpcAsyncIOTransport( + 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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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.AlloyDBAdminGrpcTransport, transports.AlloyDBAdminGrpcAsyncIOTransport]) +def test_alloy_db_admin_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_alloy_db_admin_grpc_lro_client(): + client = AlloyDBAdminClient( + 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_alloy_db_admin_grpc_lro_async_client(): + client = AlloyDBAdminAsyncClient( + 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" + backup = "whelk" + expected = "projects/{project}/locations/{location}/backups/{backup}".format(project=project, location=location, backup=backup, ) + actual = AlloyDBAdminClient.backup_path(project, location, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "octopus", + "location": "oyster", + "backup": "nudibranch", + } + path = AlloyDBAdminClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_backup_path(path) + assert expected == actual + +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) + actual = AlloyDBAdminClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = AlloyDBAdminClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_cluster_path(path) + assert expected == actual + +def test_connection_info_path(): + project = "squid" + location = "clam" + cluster = "whelk" + instance = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format(project=project, location=location, cluster=cluster, instance=instance, ) + actual = AlloyDBAdminClient.connection_info_path(project, location, cluster, instance) + assert expected == actual + + +def test_parse_connection_info_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "instance": "mussel", + } + path = AlloyDBAdminClient.connection_info_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_connection_info_path(path) + assert expected == actual + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = AlloyDBAdminClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = AlloyDBAdminClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_crypto_key_version_path(path) + assert expected == actual + +def test_instance_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + instance = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format(project=project, location=location, cluster=cluster, instance=instance, ) + actual = AlloyDBAdminClient.instance_path(project, location, cluster, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "instance": "clam", + } + path = AlloyDBAdminClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_instance_path(path) + assert expected == actual + +def test_network_path(): + project = "whelk" + network = "octopus" + expected = "projects/{project}/global/networks/{network}".format(project=project, network=network, ) + actual = AlloyDBAdminClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "oyster", + "network": "nudibranch", + } + path = AlloyDBAdminClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_network_path(path) + assert expected == actual + +def test_supported_database_flag_path(): + project = "cuttlefish" + location = "mussel" + flag = "winkle" + expected = "projects/{project}/locations/{location}/flags/{flag}".format(project=project, location=location, flag=flag, ) + actual = AlloyDBAdminClient.supported_database_flag_path(project, location, flag) + assert expected == actual + + +def test_parse_supported_database_flag_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "flag": "abalone", + } + path = AlloyDBAdminClient.supported_database_flag_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_supported_database_flag_path(path) + assert expected == actual + +def test_user_path(): + project = "squid" + location = "clam" + cluster = "whelk" + user = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format(project=project, location=location, cluster=cluster, user=user, ) + actual = AlloyDBAdminClient.user_path(project, location, cluster, user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "user": "mussel", + } + path = AlloyDBAdminClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AlloyDBAdminClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = AlloyDBAdminClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = AlloyDBAdminClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = AlloyDBAdminClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AlloyDBAdminClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = AlloyDBAdminClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = AlloyDBAdminClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = AlloyDBAdminClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.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 = AlloyDBAdminClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = AlloyDBAdminClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.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.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AlloyDBAdminTransport, '_prep_wrapped_messages') as prep: + transport_class = AlloyDBAdminClient.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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value 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 = AlloyDBAdminClient( + 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 = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AlloyDBAdminClient( + 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 = AlloyDBAdminClient( + 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", [ + (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport), + (AlloyDBAdminAsyncClient, transports.AlloyDBAdminGrpcAsyncIOTransport), +]) +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, + )