diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/.coveragerc b/owl-bot-staging/google-cloud-storage-transfer/v1/.coveragerc new file mode 100644 index 000000000000..fc2a36a640b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/storage_transfer/__init__.py + google/cloud/storage_transfer/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-storage-transfer/v1/.flake8 b/owl-bot-staging/google-cloud-storage-transfer/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/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-storage-transfer/v1/MANIFEST.in b/owl-bot-staging/google-cloud-storage-transfer/v1/MANIFEST.in new file mode 100644 index 000000000000..cacefb445196 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/storage_transfer *.py +recursive-include google/cloud/storage_transfer_v1 *.py diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/README.rst b/owl-bot-staging/google-cloud-storage-transfer/v1/README.rst new file mode 100644 index 000000000000..3d119c690ad5 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Storage Transfer 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 Storage Transfer 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-storage-transfer/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/docs/conf.py b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/conf.py new file mode 100644 index 000000000000..a2e4b917f985 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-storage-transfer 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-storage-transfer" +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-storage-transfer-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-storage-transfer.tex", + u"google-cloud-storage-transfer 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-storage-transfer", + u"Google Cloud Storage Transfer 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-storage-transfer", + u"google-cloud-storage-transfer Documentation", + author, + "google-cloud-storage-transfer", + "GAPIC library for Google Cloud Storage Transfer 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-storage-transfer/v1/docs/index.rst b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/index.rst new file mode 100644 index 000000000000..0933da115b34 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + storage_transfer_v1/services + storage_transfer_v1/types diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/services_.rst b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/services_.rst new file mode 100644 index 000000000000..01810eea751b --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Storage Transfer v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + storage_transfer_service diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/storage_transfer_service.rst b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/storage_transfer_service.rst new file mode 100644 index 000000000000..9bf5747a817b --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/storage_transfer_service.rst @@ -0,0 +1,10 @@ +StorageTransferService +---------------------------------------- + +.. automodule:: google.cloud.storage_transfer_v1.services.storage_transfer_service + :members: + :inherited-members: + +.. automodule:: google.cloud.storage_transfer_v1.services.storage_transfer_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/types_.rst b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/types_.rst new file mode 100644 index 000000000000..cd45952bc0e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/docs/storage_transfer_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Storage Transfer v1 API +============================================== + +.. automodule:: google.cloud.storage_transfer_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/__init__.py new file mode 100644 index 000000000000..aadee31287c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/__init__.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.storage_transfer import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.storage_transfer_v1.services.storage_transfer_service.client import StorageTransferServiceClient +from google.cloud.storage_transfer_v1.services.storage_transfer_service.async_client import StorageTransferServiceAsyncClient + +from google.cloud.storage_transfer_v1.types.transfer import CreateAgentPoolRequest +from google.cloud.storage_transfer_v1.types.transfer import CreateTransferJobRequest +from google.cloud.storage_transfer_v1.types.transfer import DeleteAgentPoolRequest +from google.cloud.storage_transfer_v1.types.transfer import DeleteTransferJobRequest +from google.cloud.storage_transfer_v1.types.transfer import GetAgentPoolRequest +from google.cloud.storage_transfer_v1.types.transfer import GetGoogleServiceAccountRequest +from google.cloud.storage_transfer_v1.types.transfer import GetTransferJobRequest +from google.cloud.storage_transfer_v1.types.transfer import ListAgentPoolsRequest +from google.cloud.storage_transfer_v1.types.transfer import ListAgentPoolsResponse +from google.cloud.storage_transfer_v1.types.transfer import ListTransferJobsRequest +from google.cloud.storage_transfer_v1.types.transfer import ListTransferJobsResponse +from google.cloud.storage_transfer_v1.types.transfer import PauseTransferOperationRequest +from google.cloud.storage_transfer_v1.types.transfer import ResumeTransferOperationRequest +from google.cloud.storage_transfer_v1.types.transfer import RunTransferJobRequest +from google.cloud.storage_transfer_v1.types.transfer import UpdateAgentPoolRequest +from google.cloud.storage_transfer_v1.types.transfer import UpdateTransferJobRequest +from google.cloud.storage_transfer_v1.types.transfer_types import AgentPool +from google.cloud.storage_transfer_v1.types.transfer_types import AwsAccessKey +from google.cloud.storage_transfer_v1.types.transfer_types import AwsS3CompatibleData +from google.cloud.storage_transfer_v1.types.transfer_types import AwsS3Data +from google.cloud.storage_transfer_v1.types.transfer_types import AzureBlobStorageData +from google.cloud.storage_transfer_v1.types.transfer_types import AzureCredentials +from google.cloud.storage_transfer_v1.types.transfer_types import ErrorLogEntry +from google.cloud.storage_transfer_v1.types.transfer_types import ErrorSummary +from google.cloud.storage_transfer_v1.types.transfer_types import EventStream +from google.cloud.storage_transfer_v1.types.transfer_types import GcsData +from google.cloud.storage_transfer_v1.types.transfer_types import GoogleServiceAccount +from google.cloud.storage_transfer_v1.types.transfer_types import HdfsData +from google.cloud.storage_transfer_v1.types.transfer_types import HttpData +from google.cloud.storage_transfer_v1.types.transfer_types import LoggingConfig +from google.cloud.storage_transfer_v1.types.transfer_types import MetadataOptions +from google.cloud.storage_transfer_v1.types.transfer_types import NotificationConfig +from google.cloud.storage_transfer_v1.types.transfer_types import ObjectConditions +from google.cloud.storage_transfer_v1.types.transfer_types import PosixFilesystem +from google.cloud.storage_transfer_v1.types.transfer_types import S3CompatibleMetadata +from google.cloud.storage_transfer_v1.types.transfer_types import Schedule +from google.cloud.storage_transfer_v1.types.transfer_types import TransferCounters +from google.cloud.storage_transfer_v1.types.transfer_types import TransferJob +from google.cloud.storage_transfer_v1.types.transfer_types import TransferManifest +from google.cloud.storage_transfer_v1.types.transfer_types import TransferOperation +from google.cloud.storage_transfer_v1.types.transfer_types import TransferOptions +from google.cloud.storage_transfer_v1.types.transfer_types import TransferSpec + +__all__ = ('StorageTransferServiceClient', + 'StorageTransferServiceAsyncClient', + 'CreateAgentPoolRequest', + 'CreateTransferJobRequest', + 'DeleteAgentPoolRequest', + 'DeleteTransferJobRequest', + 'GetAgentPoolRequest', + 'GetGoogleServiceAccountRequest', + 'GetTransferJobRequest', + 'ListAgentPoolsRequest', + 'ListAgentPoolsResponse', + 'ListTransferJobsRequest', + 'ListTransferJobsResponse', + 'PauseTransferOperationRequest', + 'ResumeTransferOperationRequest', + 'RunTransferJobRequest', + 'UpdateAgentPoolRequest', + 'UpdateTransferJobRequest', + 'AgentPool', + 'AwsAccessKey', + 'AwsS3CompatibleData', + 'AwsS3Data', + 'AzureBlobStorageData', + 'AzureCredentials', + 'ErrorLogEntry', + 'ErrorSummary', + 'EventStream', + 'GcsData', + 'GoogleServiceAccount', + 'HdfsData', + 'HttpData', + 'LoggingConfig', + 'MetadataOptions', + 'NotificationConfig', + 'ObjectConditions', + 'PosixFilesystem', + 'S3CompatibleMetadata', + 'Schedule', + 'TransferCounters', + 'TransferJob', + 'TransferManifest', + 'TransferOperation', + 'TransferOptions', + 'TransferSpec', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/gapic_version.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/py.typed b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/py.typed new file mode 100644 index 000000000000..ead7117d9bb3 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storage-transfer package uses inline types. diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/__init__.py new file mode 100644 index 000000000000..a4714a00adec --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/__init__.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.storage_transfer_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.storage_transfer_service import StorageTransferServiceClient +from .services.storage_transfer_service import StorageTransferServiceAsyncClient + +from .types.transfer import CreateAgentPoolRequest +from .types.transfer import CreateTransferJobRequest +from .types.transfer import DeleteAgentPoolRequest +from .types.transfer import DeleteTransferJobRequest +from .types.transfer import GetAgentPoolRequest +from .types.transfer import GetGoogleServiceAccountRequest +from .types.transfer import GetTransferJobRequest +from .types.transfer import ListAgentPoolsRequest +from .types.transfer import ListAgentPoolsResponse +from .types.transfer import ListTransferJobsRequest +from .types.transfer import ListTransferJobsResponse +from .types.transfer import PauseTransferOperationRequest +from .types.transfer import ResumeTransferOperationRequest +from .types.transfer import RunTransferJobRequest +from .types.transfer import UpdateAgentPoolRequest +from .types.transfer import UpdateTransferJobRequest +from .types.transfer_types import AgentPool +from .types.transfer_types import AwsAccessKey +from .types.transfer_types import AwsS3CompatibleData +from .types.transfer_types import AwsS3Data +from .types.transfer_types import AzureBlobStorageData +from .types.transfer_types import AzureCredentials +from .types.transfer_types import ErrorLogEntry +from .types.transfer_types import ErrorSummary +from .types.transfer_types import EventStream +from .types.transfer_types import GcsData +from .types.transfer_types import GoogleServiceAccount +from .types.transfer_types import HdfsData +from .types.transfer_types import HttpData +from .types.transfer_types import LoggingConfig +from .types.transfer_types import MetadataOptions +from .types.transfer_types import NotificationConfig +from .types.transfer_types import ObjectConditions +from .types.transfer_types import PosixFilesystem +from .types.transfer_types import S3CompatibleMetadata +from .types.transfer_types import Schedule +from .types.transfer_types import TransferCounters +from .types.transfer_types import TransferJob +from .types.transfer_types import TransferManifest +from .types.transfer_types import TransferOperation +from .types.transfer_types import TransferOptions +from .types.transfer_types import TransferSpec + +__all__ = ( + 'StorageTransferServiceAsyncClient', +'AgentPool', +'AwsAccessKey', +'AwsS3CompatibleData', +'AwsS3Data', +'AzureBlobStorageData', +'AzureCredentials', +'CreateAgentPoolRequest', +'CreateTransferJobRequest', +'DeleteAgentPoolRequest', +'DeleteTransferJobRequest', +'ErrorLogEntry', +'ErrorSummary', +'EventStream', +'GcsData', +'GetAgentPoolRequest', +'GetGoogleServiceAccountRequest', +'GetTransferJobRequest', +'GoogleServiceAccount', +'HdfsData', +'HttpData', +'ListAgentPoolsRequest', +'ListAgentPoolsResponse', +'ListTransferJobsRequest', +'ListTransferJobsResponse', +'LoggingConfig', +'MetadataOptions', +'NotificationConfig', +'ObjectConditions', +'PauseTransferOperationRequest', +'PosixFilesystem', +'ResumeTransferOperationRequest', +'RunTransferJobRequest', +'S3CompatibleMetadata', +'Schedule', +'StorageTransferServiceClient', +'TransferCounters', +'TransferJob', +'TransferManifest', +'TransferOperation', +'TransferOptions', +'TransferSpec', +'UpdateAgentPoolRequest', +'UpdateTransferJobRequest', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_metadata.json new file mode 100644 index 000000000000..6d88ff8fe2a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_metadata.json @@ -0,0 +1,238 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.storage_transfer_v1", + "protoPackage": "google.storagetransfer.v1", + "schema": "1.0", + "services": { + "StorageTransferService": { + "clients": { + "grpc": { + "libraryClient": "StorageTransferServiceClient", + "rpcs": { + "CreateAgentPool": { + "methods": [ + "create_agent_pool" + ] + }, + "CreateTransferJob": { + "methods": [ + "create_transfer_job" + ] + }, + "DeleteAgentPool": { + "methods": [ + "delete_agent_pool" + ] + }, + "DeleteTransferJob": { + "methods": [ + "delete_transfer_job" + ] + }, + "GetAgentPool": { + "methods": [ + "get_agent_pool" + ] + }, + "GetGoogleServiceAccount": { + "methods": [ + "get_google_service_account" + ] + }, + "GetTransferJob": { + "methods": [ + "get_transfer_job" + ] + }, + "ListAgentPools": { + "methods": [ + "list_agent_pools" + ] + }, + "ListTransferJobs": { + "methods": [ + "list_transfer_jobs" + ] + }, + "PauseTransferOperation": { + "methods": [ + "pause_transfer_operation" + ] + }, + "ResumeTransferOperation": { + "methods": [ + "resume_transfer_operation" + ] + }, + "RunTransferJob": { + "methods": [ + "run_transfer_job" + ] + }, + "UpdateAgentPool": { + "methods": [ + "update_agent_pool" + ] + }, + "UpdateTransferJob": { + "methods": [ + "update_transfer_job" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StorageTransferServiceAsyncClient", + "rpcs": { + "CreateAgentPool": { + "methods": [ + "create_agent_pool" + ] + }, + "CreateTransferJob": { + "methods": [ + "create_transfer_job" + ] + }, + "DeleteAgentPool": { + "methods": [ + "delete_agent_pool" + ] + }, + "DeleteTransferJob": { + "methods": [ + "delete_transfer_job" + ] + }, + "GetAgentPool": { + "methods": [ + "get_agent_pool" + ] + }, + "GetGoogleServiceAccount": { + "methods": [ + "get_google_service_account" + ] + }, + "GetTransferJob": { + "methods": [ + "get_transfer_job" + ] + }, + "ListAgentPools": { + "methods": [ + "list_agent_pools" + ] + }, + "ListTransferJobs": { + "methods": [ + "list_transfer_jobs" + ] + }, + "PauseTransferOperation": { + "methods": [ + "pause_transfer_operation" + ] + }, + "ResumeTransferOperation": { + "methods": [ + "resume_transfer_operation" + ] + }, + "RunTransferJob": { + "methods": [ + "run_transfer_job" + ] + }, + "UpdateAgentPool": { + "methods": [ + "update_agent_pool" + ] + }, + "UpdateTransferJob": { + "methods": [ + "update_transfer_job" + ] + } + } + }, + "rest": { + "libraryClient": "StorageTransferServiceClient", + "rpcs": { + "CreateAgentPool": { + "methods": [ + "create_agent_pool" + ] + }, + "CreateTransferJob": { + "methods": [ + "create_transfer_job" + ] + }, + "DeleteAgentPool": { + "methods": [ + "delete_agent_pool" + ] + }, + "DeleteTransferJob": { + "methods": [ + "delete_transfer_job" + ] + }, + "GetAgentPool": { + "methods": [ + "get_agent_pool" + ] + }, + "GetGoogleServiceAccount": { + "methods": [ + "get_google_service_account" + ] + }, + "GetTransferJob": { + "methods": [ + "get_transfer_job" + ] + }, + "ListAgentPools": { + "methods": [ + "list_agent_pools" + ] + }, + "ListTransferJobs": { + "methods": [ + "list_transfer_jobs" + ] + }, + "PauseTransferOperation": { + "methods": [ + "pause_transfer_operation" + ] + }, + "ResumeTransferOperation": { + "methods": [ + "resume_transfer_operation" + ] + }, + "RunTransferJob": { + "methods": [ + "run_transfer_job" + ] + }, + "UpdateAgentPool": { + "methods": [ + "update_agent_pool" + ] + }, + "UpdateTransferJob": { + "methods": [ + "update_transfer_job" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_version.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/py.typed b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/py.typed new file mode 100644 index 000000000000..ead7117d9bb3 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storage-transfer package uses inline types. diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/__init__.py new file mode 100644 index 000000000000..51a1c74929d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import StorageTransferServiceClient +from .async_client import StorageTransferServiceAsyncClient + +__all__ = ( + 'StorageTransferServiceClient', + 'StorageTransferServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/async_client.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/async_client.py new file mode 100644 index 000000000000..8f012dafe302 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/async_client.py @@ -0,0 +1,1743 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.storage_transfer_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_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.storage_transfer_v1.services.storage_transfer_service import pagers +from google.cloud.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +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 StorageTransferServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StorageTransferServiceGrpcAsyncIOTransport +from .client import StorageTransferServiceClient + + +class StorageTransferServiceAsyncClient: + """Storage Transfer Service and its protos. + Transfers data between between Google Cloud Storage buckets or + from a data source external to Google to a Cloud Storage bucket. + """ + + _client: StorageTransferServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StorageTransferServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StorageTransferServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StorageTransferServiceClient._DEFAULT_UNIVERSE + + agent_pools_path = staticmethod(StorageTransferServiceClient.agent_pools_path) + parse_agent_pools_path = staticmethod(StorageTransferServiceClient.parse_agent_pools_path) + common_billing_account_path = staticmethod(StorageTransferServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StorageTransferServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StorageTransferServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StorageTransferServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StorageTransferServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StorageTransferServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StorageTransferServiceClient.common_project_path) + parse_common_project_path = staticmethod(StorageTransferServiceClient.parse_common_project_path) + common_location_path = staticmethod(StorageTransferServiceClient.common_location_path) + parse_common_location_path = staticmethod(StorageTransferServiceClient.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: + StorageTransferServiceAsyncClient: The constructed client. + """ + return StorageTransferServiceClient.from_service_account_info.__func__(StorageTransferServiceAsyncClient, 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: + StorageTransferServiceAsyncClient: The constructed client. + """ + return StorageTransferServiceClient.from_service_account_file.__func__(StorageTransferServiceAsyncClient, 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 StorageTransferServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StorageTransferServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StorageTransferServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = StorageTransferServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StorageTransferServiceTransport, Callable[..., StorageTransferServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage transfer service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StorageTransferServiceTransport,Callable[..., StorageTransferServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StorageTransferServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = StorageTransferServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_google_service_account(self, + request: Optional[Union[transfer.GetGoogleServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.GoogleServiceAccount: + r"""Returns the Google service account that is used by + Storage Transfer Service to access buckets in the + project where transfers run or in other projects. Each + Google service account is associated with one Google + Cloud project. Users + should add this service account to the Google Cloud + Storage bucket ACLs to grant access to Storage Transfer + Service. This service account is created and owned by + Storage Transfer Service and can only be used by Storage + Transfer Service. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_get_google_service_account(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetGoogleServiceAccountRequest( + project_id="project_id_value", + ) + + # Make the request + response = await client.get_google_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.GetGoogleServiceAccountRequest, dict]]): + The request object. Request passed to + GetGoogleServiceAccount. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.GoogleServiceAccount: + Google service account + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetGoogleServiceAccountRequest): + request = transfer.GetGoogleServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_google_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_transfer_job(self, + request: Optional[Union[transfer.CreateTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Creates a transfer job that runs periodically. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_create_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.CreateTransferJobRequest( + ) + + # Make the request + response = await client.create_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.CreateTransferJobRequest, dict]]): + The request object. Request passed to CreateTransferJob. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.CreateTransferJobRequest): + request = transfer.CreateTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_transfer_job] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_transfer_job(self, + request: Optional[Union[transfer.UpdateTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Updates a transfer job. Updating a job's transfer spec does not + affect transfer operations that are running already. + + **Note:** The job's + [status][google.storagetransfer.v1.TransferJob.status] field can + be modified using this RPC (for example, to set a job's status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED], + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + or + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED]). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_update_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.UpdateTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = await client.update_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.UpdateTransferJobRequest, dict]]): + The request object. Request passed to UpdateTransferJob. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.UpdateTransferJobRequest): + request = transfer.UpdateTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_transfer_job(self, + request: Optional[Union[transfer.GetTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Gets a transfer job. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_get_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = await client.get_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.GetTransferJobRequest, dict]]): + The request object. Request passed to GetTransferJob. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetTransferJobRequest): + request = transfer.GetTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_transfer_jobs(self, + request: Optional[Union[transfer.ListTransferJobsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferJobsAsyncPager: + r"""Lists transfer jobs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_list_transfer_jobs(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListTransferJobsRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_transfer_jobs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.ListTransferJobsRequest, dict]]): + The request object. ``projectId``, ``jobNames``, and ``jobStatuses`` are + query parameters that can be specified when listing + transfer jobs. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.services.storage_transfer_service.pagers.ListTransferJobsAsyncPager: + Response from ListTransferJobs. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ListTransferJobsRequest): + request = transfer.ListTransferJobsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_transfer_jobs] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTransferJobsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def pause_transfer_operation(self, + request: Optional[Union[transfer.PauseTransferOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Pauses a transfer operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_pause_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.PauseTransferOperationRequest( + name="name_value", + ) + + # Make the request + await client.pause_transfer_operation(request=request) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.PauseTransferOperationRequest, dict]]): + The request object. Request passed to + PauseTransferOperation. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.PauseTransferOperationRequest): + request = transfer.PauseTransferOperationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.pause_transfer_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def resume_transfer_operation(self, + request: Optional[Union[transfer.ResumeTransferOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Resumes a transfer operation that is paused. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_resume_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ResumeTransferOperationRequest( + name="name_value", + ) + + # Make the request + await client.resume_transfer_operation(request=request) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.ResumeTransferOperationRequest, dict]]): + The request object. Request passed to + ResumeTransferOperation. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ResumeTransferOperationRequest): + request = transfer.ResumeTransferOperationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.resume_transfer_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def run_transfer_job(self, + request: Optional[Union[transfer.RunTransferJobRequest, 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"""Starts a new operation for the specified transfer job. A + ``TransferJob`` has a maximum of one active + ``TransferOperation``. If this method is called while a + ``TransferOperation`` is active, an error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_run_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.RunTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + operation = client.run_transfer_job(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.RunTransferJobRequest, dict]]): + The request object. Request passed to RunTransferJob. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.RunTransferJobRequest): + request = transfer.RunTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.run_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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=transfer_types.TransferOperation, + ) + + # Done; return the response. + return response + + async def delete_transfer_job(self, + request: Optional[Union[transfer.DeleteTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a transfer job. Deleting a transfer job sets its status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_delete_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + await client.delete_transfer_job(request=request) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.DeleteTransferJobRequest, dict]]): + The request object. Request passed to DeleteTransferJob. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.DeleteTransferJobRequest): + request = transfer.DeleteTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_agent_pool(self, + request: Optional[Union[transfer.CreateAgentPoolRequest, dict]] = None, + *, + project_id: Optional[str] = None, + agent_pool: Optional[transfer_types.AgentPool] = None, + agent_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.AgentPool: + r"""Creates an agent pool resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_create_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.CreateAgentPoolRequest( + project_id="project_id_value", + agent_pool=agent_pool, + agent_pool_id="agent_pool_id_value", + ) + + # Make the request + response = await client.create_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.CreateAgentPoolRequest, dict]]): + The request object. Specifies the request passed to + CreateAgentPool. + project_id (:class:`str`): + Required. The ID of the Google Cloud + project that owns the agent pool. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_pool (:class:`google.cloud.storage_transfer_v1.types.AgentPool`): + Required. The agent pool to create. + This corresponds to the ``agent_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_pool_id (:class:`str`): + Required. The ID of the agent pool to create. + + The ``agent_pool_id`` must meet the following + requirements: + + - Length of 128 characters or less. + - Not start with the string ``goog``. + - Start with a lowercase ASCII character, followed by: + + - Zero or more: lowercase Latin alphabet characters, + numerals, hyphens (``-``), periods (``.``), + underscores (``_``), or tildes (``~``). + - One or more numerals or lowercase ASCII + characters. + + As expressed by the regular expression: + ``^(?!goog)[a-z]([a-z0-9-._~]*[a-z0-9])?$``. + + This corresponds to the ``agent_pool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, agent_pool, agent_pool_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.CreateAgentPoolRequest): + request = transfer.CreateAgentPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if agent_pool is not None: + request.agent_pool = agent_pool + if agent_pool_id is not None: + request.agent_pool_id = agent_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_agent_pool(self, + request: Optional[Union[transfer.UpdateAgentPoolRequest, dict]] = None, + *, + agent_pool: Optional[transfer_types.AgentPool] = 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]] = (), + ) -> transfer_types.AgentPool: + r"""Updates an existing agent pool resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_update_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.UpdateAgentPoolRequest( + agent_pool=agent_pool, + ) + + # Make the request + response = await client.update_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.UpdateAgentPoolRequest, dict]]): + The request object. Specifies the request passed to + UpdateAgentPool. + agent_pool (:class:`google.cloud.storage_transfer_v1.types.AgentPool`): + Required. The agent pool to update. ``agent_pool`` is + expected to specify following fields: + + - [name][google.storagetransfer.v1.AgentPool.name] + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + An ``UpdateAgentPoolRequest`` with any other fields + is rejected with the error + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + + This corresponds to the ``agent_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The [field mask] + (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf) + of the fields in ``agentPool`` to update in this + request. The following ``agentPool`` fields can be + updated: + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.UpdateAgentPoolRequest): + request = transfer.UpdateAgentPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent_pool is not None: + request.agent_pool = agent_pool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent_pool.name", request.agent_pool.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_pool(self, + request: Optional[Union[transfer.GetAgentPoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.AgentPool: + r"""Gets an agent pool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_get_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetAgentPoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.GetAgentPoolRequest, dict]]): + The request object. Specifies the request passed to + GetAgentPool. + name (:class:`str`): + Required. The name of the agent pool + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetAgentPoolRequest): + request = transfer.GetAgentPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_agent_pools(self, + request: Optional[Union[transfer.ListAgentPoolsRequest, dict]] = None, + *, + project_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentPoolsAsyncPager: + r"""Lists agent pools. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_list_agent_pools(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListAgentPoolsRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_agent_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest, dict]]): + The request object. The request passed to ListAgentPools. + project_id (:class:`str`): + Required. The ID of the Google Cloud + project that owns the job. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.storage_transfer_v1.services.storage_transfer_service.pagers.ListAgentPoolsAsyncPager: + Response from ListAgentPools. + + 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([project_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ListAgentPoolsRequest): + request = transfer.ListAgentPoolsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_agent_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAgentPoolsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_agent_pool(self, + request: Optional[Union[transfer.DeleteAgentPoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an agent pool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + async def sample_delete_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteAgentPoolRequest( + name="name_value", + ) + + # Make the request + await client.delete_agent_pool(request=request) + + Args: + request (Optional[Union[google.cloud.storage_transfer_v1.types.DeleteAgentPoolRequest, dict]]): + The request object. Specifies the request passed to + DeleteAgentPool. + name (:class:`str`): + Required. The name of the agent pool + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.DeleteAgentPoolRequest): + request = transfer.DeleteAgentPoolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def cancel_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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + 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_async.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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "StorageTransferServiceAsyncClient": + 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__ = ( + "StorageTransferServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/client.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/client.py new file mode 100644 index 000000000000..03af2f094ecc --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/client.py @@ -0,0 +1,2095 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.storage_transfer_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, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.storage_transfer_v1.services.storage_transfer_service import pagers +from google.cloud.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +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 StorageTransferServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StorageTransferServiceGrpcTransport +from .transports.grpc_asyncio import StorageTransferServiceGrpcAsyncIOTransport +from .transports.rest import StorageTransferServiceRestTransport + + +class StorageTransferServiceClientMeta(type): + """Metaclass for the StorageTransferService 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[StorageTransferServiceTransport]] + _transport_registry["grpc"] = StorageTransferServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StorageTransferServiceGrpcAsyncIOTransport + _transport_registry["rest"] = StorageTransferServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StorageTransferServiceTransport]: + """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 StorageTransferServiceClient(metaclass=StorageTransferServiceClientMeta): + """Storage Transfer Service and its protos. + Transfers data between between Google Cloud Storage buckets or + from a data source external to Google to a Cloud Storage bucket. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "storagetransfer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "storagetransfer.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StorageTransferServiceClient: 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: + StorageTransferServiceClient: 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) -> StorageTransferServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StorageTransferServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_pools_path(project_id: str,agent_pool_id: str,) -> str: + """Returns a fully-qualified agent_pools string.""" + return "projects/{project_id}/agentPools/{agent_pool_id}".format(project_id=project_id, agent_pool_id=agent_pool_id, ) + + @staticmethod + def parse_agent_pools_path(path: str) -> Dict[str,str]: + """Parses a agent_pools path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agentPools/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = StorageTransferServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = StorageTransferServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StorageTransferServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = StorageTransferServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + StorageTransferServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StorageTransferServiceTransport, Callable[..., StorageTransferServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage transfer service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,StorageTransferServiceTransport,Callable[..., StorageTransferServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StorageTransferServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StorageTransferServiceClient._read_environment_variables() + self._client_cert_source = StorageTransferServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = StorageTransferServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StorageTransferServiceTransport) + if transport_provided: + # transport is a StorageTransferServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(StorageTransferServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + StorageTransferServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[StorageTransferServiceTransport], Callable[..., StorageTransferServiceTransport]] = ( + StorageTransferServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StorageTransferServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_google_service_account(self, + request: Optional[Union[transfer.GetGoogleServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.GoogleServiceAccount: + r"""Returns the Google service account that is used by + Storage Transfer Service to access buckets in the + project where transfers run or in other projects. Each + Google service account is associated with one Google + Cloud project. Users + should add this service account to the Google Cloud + Storage bucket ACLs to grant access to Storage Transfer + Service. This service account is created and owned by + Storage Transfer Service and can only be used by Storage + Transfer Service. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_get_google_service_account(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetGoogleServiceAccountRequest( + project_id="project_id_value", + ) + + # Make the request + response = client.get_google_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.GetGoogleServiceAccountRequest, dict]): + The request object. Request passed to + GetGoogleServiceAccount. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.storage_transfer_v1.types.GoogleServiceAccount: + Google service account + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetGoogleServiceAccountRequest): + request = transfer.GetGoogleServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_google_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_transfer_job(self, + request: Optional[Union[transfer.CreateTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Creates a transfer job that runs periodically. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_create_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.CreateTransferJobRequest( + ) + + # Make the request + response = client.create_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.CreateTransferJobRequest, dict]): + The request object. Request passed to CreateTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.CreateTransferJobRequest): + request = transfer.CreateTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_transfer_job] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_transfer_job(self, + request: Optional[Union[transfer.UpdateTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Updates a transfer job. Updating a job's transfer spec does not + affect transfer operations that are running already. + + **Note:** The job's + [status][google.storagetransfer.v1.TransferJob.status] field can + be modified using this RPC (for example, to set a job's status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED], + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + or + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED]). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_update_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.UpdateTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = client.update_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.UpdateTransferJobRequest, dict]): + The request object. Request passed to UpdateTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.UpdateTransferJobRequest): + request = transfer.UpdateTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_transfer_job(self, + request: Optional[Union[transfer.GetTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.TransferJob: + r"""Gets a transfer job. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_get_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = client.get_transfer_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.GetTransferJobRequest, dict]): + The request object. Request passed to GetTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.storage_transfer_v1.types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetTransferJobRequest): + request = transfer.GetTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_transfer_jobs(self, + request: Optional[Union[transfer.ListTransferJobsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferJobsPager: + r"""Lists transfer jobs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_list_transfer_jobs(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListTransferJobsRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_transfer_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.ListTransferJobsRequest, dict]): + The request object. ``projectId``, ``jobNames``, and ``jobStatuses`` are + query parameters that can be specified when listing + transfer jobs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.storage_transfer_v1.services.storage_transfer_service.pagers.ListTransferJobsPager: + Response from ListTransferJobs. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ListTransferJobsRequest): + request = transfer.ListTransferJobsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transfer_jobs] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTransferJobsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def pause_transfer_operation(self, + request: Optional[Union[transfer.PauseTransferOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Pauses a transfer operation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_pause_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.PauseTransferOperationRequest( + name="name_value", + ) + + # Make the request + client.pause_transfer_operation(request=request) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.PauseTransferOperationRequest, dict]): + The request object. Request passed to + PauseTransferOperation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.PauseTransferOperationRequest): + request = transfer.PauseTransferOperationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause_transfer_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def resume_transfer_operation(self, + request: Optional[Union[transfer.ResumeTransferOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Resumes a transfer operation that is paused. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_resume_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ResumeTransferOperationRequest( + name="name_value", + ) + + # Make the request + client.resume_transfer_operation(request=request) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.ResumeTransferOperationRequest, dict]): + The request object. Request passed to + ResumeTransferOperation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ResumeTransferOperationRequest): + request = transfer.ResumeTransferOperationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume_transfer_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def run_transfer_job(self, + request: Optional[Union[transfer.RunTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Starts a new operation for the specified transfer job. A + ``TransferJob`` has a maximum of one active + ``TransferOperation``. If this method is called while a + ``TransferOperation`` is active, an error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_run_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.RunTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + operation = client.run_transfer_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.RunTransferJobRequest, dict]): + The request object. Request passed to RunTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.RunTransferJobRequest): + request = transfer.RunTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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=transfer_types.TransferOperation, + ) + + # Done; return the response. + return response + + def delete_transfer_job(self, + request: Optional[Union[transfer.DeleteTransferJobRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a transfer job. Deleting a transfer job sets its status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_delete_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + client.delete_transfer_job(request=request) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.DeleteTransferJobRequest, dict]): + The request object. Request passed to DeleteTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.DeleteTransferJobRequest): + request = transfer.DeleteTransferJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_transfer_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("job_name", request.job_name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_agent_pool(self, + request: Optional[Union[transfer.CreateAgentPoolRequest, dict]] = None, + *, + project_id: Optional[str] = None, + agent_pool: Optional[transfer_types.AgentPool] = None, + agent_pool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.AgentPool: + r"""Creates an agent pool resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_create_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.CreateAgentPoolRequest( + project_id="project_id_value", + agent_pool=agent_pool, + agent_pool_id="agent_pool_id_value", + ) + + # Make the request + response = client.create_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.CreateAgentPoolRequest, dict]): + The request object. Specifies the request passed to + CreateAgentPool. + project_id (str): + Required. The ID of the Google Cloud + project that owns the agent pool. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_pool (google.cloud.storage_transfer_v1.types.AgentPool): + Required. The agent pool to create. + This corresponds to the ``agent_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_pool_id (str): + Required. The ID of the agent pool to create. + + The ``agent_pool_id`` must meet the following + requirements: + + - Length of 128 characters or less. + - Not start with the string ``goog``. + - Start with a lowercase ASCII character, followed by: + + - Zero or more: lowercase Latin alphabet characters, + numerals, hyphens (``-``), periods (``.``), + underscores (``_``), or tildes (``~``). + - One or more numerals or lowercase ASCII + characters. + + As expressed by the regular expression: + ``^(?!goog)[a-z]([a-z0-9-._~]*[a-z0-9])?$``. + + This corresponds to the ``agent_pool_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.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, agent_pool, agent_pool_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.CreateAgentPoolRequest): + request = transfer.CreateAgentPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if agent_pool is not None: + request.agent_pool = agent_pool + if agent_pool_id is not None: + request.agent_pool_id = agent_pool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_agent_pool(self, + request: Optional[Union[transfer.UpdateAgentPoolRequest, dict]] = None, + *, + agent_pool: Optional[transfer_types.AgentPool] = 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]] = (), + ) -> transfer_types.AgentPool: + r"""Updates an existing agent pool resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_update_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.UpdateAgentPoolRequest( + agent_pool=agent_pool, + ) + + # Make the request + response = client.update_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.UpdateAgentPoolRequest, dict]): + The request object. Specifies the request passed to + UpdateAgentPool. + agent_pool (google.cloud.storage_transfer_v1.types.AgentPool): + Required. The agent pool to update. ``agent_pool`` is + expected to specify following fields: + + - [name][google.storagetransfer.v1.AgentPool.name] + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + An ``UpdateAgentPoolRequest`` with any other fields + is rejected with the error + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + + This corresponds to the ``agent_pool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The [field mask] + (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf) + of the fields in ``agentPool`` to update in this + request. The following ``agentPool`` fields can be + updated: + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + + 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.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent_pool, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.UpdateAgentPoolRequest): + request = transfer.UpdateAgentPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent_pool is not None: + request.agent_pool = agent_pool + 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_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent_pool.name", request.agent_pool.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_pool(self, + request: Optional[Union[transfer.GetAgentPoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer_types.AgentPool: + r"""Gets an agent pool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_get_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetAgentPoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_agent_pool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.GetAgentPoolRequest, dict]): + The request object. Specifies the request passed to + GetAgentPool. + name (str): + Required. The name of the agent pool + to get. + + 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.storage_transfer_v1.types.AgentPool: + Represents an agent pool. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.GetAgentPoolRequest): + request = transfer.GetAgentPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_agent_pools(self, + request: Optional[Union[transfer.ListAgentPoolsRequest, dict]] = None, + *, + project_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentPoolsPager: + r"""Lists agent pools. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_list_agent_pools(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListAgentPoolsRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_agent_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest, dict]): + The request object. The request passed to ListAgentPools. + project_id (str): + Required. The ID of the Google Cloud + project that owns the job. + + This corresponds to the ``project_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.storage_transfer_v1.services.storage_transfer_service.pagers.ListAgentPoolsPager: + Response from ListAgentPools. + + 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([project_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.ListAgentPoolsRequest): + request = transfer.ListAgentPoolsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_agent_pools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project_id", request.project_id), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAgentPoolsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_agent_pool(self, + request: Optional[Union[transfer.DeleteAgentPoolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an agent pool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import storage_transfer_v1 + + def sample_delete_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteAgentPoolRequest( + name="name_value", + ) + + # Make the request + client.delete_agent_pool(request=request) + + Args: + request (Union[google.cloud.storage_transfer_v1.types.DeleteAgentPoolRequest, dict]): + The request object. Specifies the request passed to + DeleteAgentPool. + name (str): + Required. The name of the agent pool + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, transfer.DeleteAgentPoolRequest): + request = transfer.DeleteAgentPoolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_agent_pool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "StorageTransferServiceClient": + 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def cancel_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "StorageTransferServiceClient", +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/pagers.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/pagers.py new file mode 100644 index 000000000000..b807a6a822ba --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/pagers.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types + + +class ListTransferJobsPager: + """A pager for iterating through ``list_transfer_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_transfer_v1.types.ListTransferJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transfer_jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransferJobs`` requests and continue to iterate + through the ``transfer_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_transfer_v1.types.ListTransferJobsResponse` + 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[..., transfer.ListTransferJobsResponse], + request: transfer.ListTransferJobsRequest, + response: transfer.ListTransferJobsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storage_transfer_v1.types.ListTransferJobsRequest): + The initial request object. + response (google.cloud.storage_transfer_v1.types.ListTransferJobsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transfer.ListTransferJobsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[transfer.ListTransferJobsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[transfer_types.TransferJob]: + for page in self.pages: + yield from page.transfer_jobs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferJobsAsyncPager: + """A pager for iterating through ``list_transfer_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_transfer_v1.types.ListTransferJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transfer_jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransferJobs`` requests and continue to iterate + through the ``transfer_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_transfer_v1.types.ListTransferJobsResponse` + 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[transfer.ListTransferJobsResponse]], + request: transfer.ListTransferJobsRequest, + response: transfer.ListTransferJobsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storage_transfer_v1.types.ListTransferJobsRequest): + The initial request object. + response (google.cloud.storage_transfer_v1.types.ListTransferJobsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transfer.ListTransferJobsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[transfer.ListTransferJobsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[transfer_types.TransferJob]: + async def async_generator(): + async for page in self.pages: + for response in page.transfer_jobs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAgentPoolsPager: + """A pager for iterating through ``list_agent_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agent_pools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAgentPools`` requests and continue to iterate + through the ``agent_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse` + 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[..., transfer.ListAgentPoolsResponse], + request: transfer.ListAgentPoolsRequest, + response: transfer.ListAgentPoolsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest): + The initial request object. + response (google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transfer.ListAgentPoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[transfer.ListAgentPoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[transfer_types.AgentPool]: + for page in self.pages: + yield from page.agent_pools + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAgentPoolsAsyncPager: + """A pager for iterating through ``list_agent_pools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agent_pools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAgentPools`` requests and continue to iterate + through the ``agent_pools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse` + 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[transfer.ListAgentPoolsResponse]], + request: transfer.ListAgentPoolsRequest, + response: transfer.ListAgentPoolsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest): + The initial request object. + response (google.cloud.storage_transfer_v1.types.ListAgentPoolsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transfer.ListAgentPoolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[transfer.ListAgentPoolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[transfer_types.AgentPool]: + async def async_generator(): + async for page in self.pages: + for response in page.agent_pools: + 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-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/__init__.py new file mode 100644 index 000000000000..76e12d4d8a4d --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import StorageTransferServiceTransport +from .grpc import StorageTransferServiceGrpcTransport +from .grpc_asyncio import StorageTransferServiceGrpcAsyncIOTransport +from .rest import StorageTransferServiceRestTransport +from .rest import StorageTransferServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StorageTransferServiceTransport]] +_transport_registry['grpc'] = StorageTransferServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StorageTransferServiceGrpcAsyncIOTransport +_transport_registry['rest'] = StorageTransferServiceRestTransport + +__all__ = ( + 'StorageTransferServiceTransport', + 'StorageTransferServiceGrpcTransport', + 'StorageTransferServiceGrpcAsyncIOTransport', + 'StorageTransferServiceRestTransport', + 'StorageTransferServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/base.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/base.py new file mode 100644 index 000000000000..daae0b31d287 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/base.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.storage_transfer_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.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +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 StorageTransferServiceTransport(abc.ABC): + """Abstract transport class for StorageTransferService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'storagetransfer.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storagetransfer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_google_service_account: gapic_v1.method.wrap_method( + self.get_google_service_account, + default_timeout=None, + client_info=client_info, + ), + self.create_transfer_job: gapic_v1.method.wrap_method( + self.create_transfer_job, + default_timeout=60.0, + client_info=client_info, + ), + self.update_transfer_job: gapic_v1.method.wrap_method( + self.update_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.get_transfer_job: gapic_v1.method.wrap_method( + self.get_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.list_transfer_jobs: gapic_v1.method.wrap_method( + self.list_transfer_jobs, + default_timeout=None, + client_info=client_info, + ), + self.pause_transfer_operation: gapic_v1.method.wrap_method( + self.pause_transfer_operation, + default_timeout=None, + client_info=client_info, + ), + self.resume_transfer_operation: gapic_v1.method.wrap_method( + self.resume_transfer_operation, + default_timeout=None, + client_info=client_info, + ), + self.run_transfer_job: gapic_v1.method.wrap_method( + self.run_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.delete_transfer_job: gapic_v1.method.wrap_method( + self.delete_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.create_agent_pool: gapic_v1.method.wrap_method( + self.create_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.update_agent_pool: gapic_v1.method.wrap_method( + self.update_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_pool: gapic_v1.method.wrap_method( + self.get_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.list_agent_pools: gapic_v1.method.wrap_method( + self.list_agent_pools, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent_pool: gapic_v1.method.wrap_method( + self.delete_agent_pool, + 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 get_google_service_account(self) -> Callable[ + [transfer.GetGoogleServiceAccountRequest], + Union[ + transfer_types.GoogleServiceAccount, + Awaitable[transfer_types.GoogleServiceAccount] + ]]: + raise NotImplementedError() + + @property + def create_transfer_job(self) -> Callable[ + [transfer.CreateTransferJobRequest], + Union[ + transfer_types.TransferJob, + Awaitable[transfer_types.TransferJob] + ]]: + raise NotImplementedError() + + @property + def update_transfer_job(self) -> Callable[ + [transfer.UpdateTransferJobRequest], + Union[ + transfer_types.TransferJob, + Awaitable[transfer_types.TransferJob] + ]]: + raise NotImplementedError() + + @property + def get_transfer_job(self) -> Callable[ + [transfer.GetTransferJobRequest], + Union[ + transfer_types.TransferJob, + Awaitable[transfer_types.TransferJob] + ]]: + raise NotImplementedError() + + @property + def list_transfer_jobs(self) -> Callable[ + [transfer.ListTransferJobsRequest], + Union[ + transfer.ListTransferJobsResponse, + Awaitable[transfer.ListTransferJobsResponse] + ]]: + raise NotImplementedError() + + @property + def pause_transfer_operation(self) -> Callable[ + [transfer.PauseTransferOperationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def resume_transfer_operation(self) -> Callable[ + [transfer.ResumeTransferOperationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def run_transfer_job(self) -> Callable[ + [transfer.RunTransferJobRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_transfer_job(self) -> Callable[ + [transfer.DeleteTransferJobRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_agent_pool(self) -> Callable[ + [transfer.CreateAgentPoolRequest], + Union[ + transfer_types.AgentPool, + Awaitable[transfer_types.AgentPool] + ]]: + raise NotImplementedError() + + @property + def update_agent_pool(self) -> Callable[ + [transfer.UpdateAgentPoolRequest], + Union[ + transfer_types.AgentPool, + Awaitable[transfer_types.AgentPool] + ]]: + raise NotImplementedError() + + @property + def get_agent_pool(self) -> Callable[ + [transfer.GetAgentPoolRequest], + Union[ + transfer_types.AgentPool, + Awaitable[transfer_types.AgentPool] + ]]: + raise NotImplementedError() + + @property + def list_agent_pools(self) -> Callable[ + [transfer.ListAgentPoolsRequest], + Union[ + transfer.ListAgentPoolsResponse, + Awaitable[transfer.ListAgentPoolsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_agent_pool(self) -> Callable[ + [transfer.DeleteAgentPoolRequest], + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'StorageTransferServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc.py new file mode 100644 index 000000000000..e193151389e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import 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.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import StorageTransferServiceTransport, DEFAULT_CLIENT_INFO + + +class StorageTransferServiceGrpcTransport(StorageTransferServiceTransport): + """gRPC backend transport for StorageTransferService. + + Storage Transfer Service and its protos. + Transfers data between between Google Cloud Storage buckets or + from a data source external to Google to a Cloud Storage bucket. + + 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 = 'storagetransfer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storagetransfer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + 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 isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'storagetransfer.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 get_google_service_account(self) -> Callable[ + [transfer.GetGoogleServiceAccountRequest], + transfer_types.GoogleServiceAccount]: + r"""Return a callable for the get google service account method over gRPC. + + Returns the Google service account that is used by + Storage Transfer Service to access buckets in the + project where transfers run or in other projects. Each + Google service account is associated with one Google + Cloud project. Users + should add this service account to the Google Cloud + Storage bucket ACLs to grant access to Storage Transfer + Service. This service account is created and owned by + Storage Transfer Service and can only be used by Storage + Transfer Service. + + Returns: + Callable[[~.GetGoogleServiceAccountRequest], + ~.GoogleServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_service_account' not in self._stubs: + self._stubs['get_google_service_account'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetGoogleServiceAccount', + request_serializer=transfer.GetGoogleServiceAccountRequest.serialize, + response_deserializer=transfer_types.GoogleServiceAccount.deserialize, + ) + return self._stubs['get_google_service_account'] + + @property + def create_transfer_job(self) -> Callable[ + [transfer.CreateTransferJobRequest], + transfer_types.TransferJob]: + r"""Return a callable for the create transfer job method over gRPC. + + Creates a transfer job that runs periodically. + + Returns: + Callable[[~.CreateTransferJobRequest], + ~.TransferJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['create_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/CreateTransferJob', + request_serializer=transfer.CreateTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['create_transfer_job'] + + @property + def update_transfer_job(self) -> Callable[ + [transfer.UpdateTransferJobRequest], + transfer_types.TransferJob]: + r"""Return a callable for the update transfer job method over gRPC. + + Updates a transfer job. Updating a job's transfer spec does not + affect transfer operations that are running already. + + **Note:** The job's + [status][google.storagetransfer.v1.TransferJob.status] field can + be modified using this RPC (for example, to set a job's status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED], + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + or + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED]). + + Returns: + Callable[[~.UpdateTransferJobRequest], + ~.TransferJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['update_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/UpdateTransferJob', + request_serializer=transfer.UpdateTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['update_transfer_job'] + + @property + def get_transfer_job(self) -> Callable[ + [transfer.GetTransferJobRequest], + transfer_types.TransferJob]: + r"""Return a callable for the get transfer job method over gRPC. + + Gets a transfer job. + + Returns: + Callable[[~.GetTransferJobRequest], + ~.TransferJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['get_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetTransferJob', + request_serializer=transfer.GetTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['get_transfer_job'] + + @property + def list_transfer_jobs(self) -> Callable[ + [transfer.ListTransferJobsRequest], + transfer.ListTransferJobsResponse]: + r"""Return a callable for the list transfer jobs method over gRPC. + + Lists transfer jobs. + + Returns: + Callable[[~.ListTransferJobsRequest], + ~.ListTransferJobsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_jobs' not in self._stubs: + self._stubs['list_transfer_jobs'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ListTransferJobs', + request_serializer=transfer.ListTransferJobsRequest.serialize, + response_deserializer=transfer.ListTransferJobsResponse.deserialize, + ) + return self._stubs['list_transfer_jobs'] + + @property + def pause_transfer_operation(self) -> Callable[ + [transfer.PauseTransferOperationRequest], + empty_pb2.Empty]: + r"""Return a callable for the pause transfer operation method over gRPC. + + Pauses a transfer operation. + + Returns: + Callable[[~.PauseTransferOperationRequest], + ~.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 'pause_transfer_operation' not in self._stubs: + self._stubs['pause_transfer_operation'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/PauseTransferOperation', + request_serializer=transfer.PauseTransferOperationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['pause_transfer_operation'] + + @property + def resume_transfer_operation(self) -> Callable[ + [transfer.ResumeTransferOperationRequest], + empty_pb2.Empty]: + r"""Return a callable for the resume transfer operation method over gRPC. + + Resumes a transfer operation that is paused. + + Returns: + Callable[[~.ResumeTransferOperationRequest], + ~.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 'resume_transfer_operation' not in self._stubs: + self._stubs['resume_transfer_operation'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ResumeTransferOperation', + request_serializer=transfer.ResumeTransferOperationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['resume_transfer_operation'] + + @property + def run_transfer_job(self) -> Callable[ + [transfer.RunTransferJobRequest], + operations_pb2.Operation]: + r"""Return a callable for the run transfer job method over gRPC. + + Starts a new operation for the specified transfer job. A + ``TransferJob`` has a maximum of one active + ``TransferOperation``. If this method is called while a + ``TransferOperation`` is active, an error is returned. + + Returns: + Callable[[~.RunTransferJobRequest], + ~.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 'run_transfer_job' not in self._stubs: + self._stubs['run_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/RunTransferJob', + request_serializer=transfer.RunTransferJobRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_transfer_job'] + + @property + def delete_transfer_job(self) -> Callable[ + [transfer.DeleteTransferJobRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transfer job method over gRPC. + + Deletes a transfer job. Deleting a transfer job sets its status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED]. + + Returns: + Callable[[~.DeleteTransferJobRequest], + ~.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_transfer_job' not in self._stubs: + self._stubs['delete_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/DeleteTransferJob', + request_serializer=transfer.DeleteTransferJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_job'] + + @property + def create_agent_pool(self) -> Callable[ + [transfer.CreateAgentPoolRequest], + transfer_types.AgentPool]: + r"""Return a callable for the create agent pool method over gRPC. + + Creates an agent pool resource. + + Returns: + Callable[[~.CreateAgentPoolRequest], + ~.AgentPool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['create_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/CreateAgentPool', + request_serializer=transfer.CreateAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['create_agent_pool'] + + @property + def update_agent_pool(self) -> Callable[ + [transfer.UpdateAgentPoolRequest], + transfer_types.AgentPool]: + r"""Return a callable for the update agent pool method over gRPC. + + Updates an existing agent pool resource. + + Returns: + Callable[[~.UpdateAgentPoolRequest], + ~.AgentPool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['update_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/UpdateAgentPool', + request_serializer=transfer.UpdateAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['update_agent_pool'] + + @property + def get_agent_pool(self) -> Callable[ + [transfer.GetAgentPoolRequest], + transfer_types.AgentPool]: + r"""Return a callable for the get agent pool method over gRPC. + + Gets an agent pool. + + Returns: + Callable[[~.GetAgentPoolRequest], + ~.AgentPool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['get_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetAgentPool', + request_serializer=transfer.GetAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['get_agent_pool'] + + @property + def list_agent_pools(self) -> Callable[ + [transfer.ListAgentPoolsRequest], + transfer.ListAgentPoolsResponse]: + r"""Return a callable for the list agent pools method over gRPC. + + Lists agent pools. + + Returns: + Callable[[~.ListAgentPoolsRequest], + ~.ListAgentPoolsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pools' not in self._stubs: + self._stubs['list_agent_pools'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ListAgentPools', + request_serializer=transfer.ListAgentPoolsRequest.serialize, + response_deserializer=transfer.ListAgentPoolsResponse.deserialize, + ) + return self._stubs['list_agent_pools'] + + @property + def delete_agent_pool(self) -> Callable[ + [transfer.DeleteAgentPoolRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete agent pool method over gRPC. + + Deletes an agent pool. + + Returns: + Callable[[~.DeleteAgentPoolRequest], + ~.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_agent_pool' not in self._stubs: + self._stubs['delete_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/DeleteAgentPool', + request_serializer=transfer.DeleteAgentPoolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent_pool'] + + def close(self): + self.grpc_channel.close() + + @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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'StorageTransferServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..22ce03d5ee38 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/grpc_asyncio.py @@ -0,0 +1,784 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.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.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import StorageTransferServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StorageTransferServiceGrpcTransport + + +class StorageTransferServiceGrpcAsyncIOTransport(StorageTransferServiceTransport): + """gRPC AsyncIO backend transport for StorageTransferService. + + Storage Transfer Service and its protos. + Transfers data between between Google Cloud Storage buckets or + from a data source external to Google to a Cloud Storage bucket. + + 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 = 'storagetransfer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'storagetransfer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storagetransfer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + 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 isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 get_google_service_account(self) -> Callable[ + [transfer.GetGoogleServiceAccountRequest], + Awaitable[transfer_types.GoogleServiceAccount]]: + r"""Return a callable for the get google service account method over gRPC. + + Returns the Google service account that is used by + Storage Transfer Service to access buckets in the + project where transfers run or in other projects. Each + Google service account is associated with one Google + Cloud project. Users + should add this service account to the Google Cloud + Storage bucket ACLs to grant access to Storage Transfer + Service. This service account is created and owned by + Storage Transfer Service and can only be used by Storage + Transfer Service. + + Returns: + Callable[[~.GetGoogleServiceAccountRequest], + Awaitable[~.GoogleServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_google_service_account' not in self._stubs: + self._stubs['get_google_service_account'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetGoogleServiceAccount', + request_serializer=transfer.GetGoogleServiceAccountRequest.serialize, + response_deserializer=transfer_types.GoogleServiceAccount.deserialize, + ) + return self._stubs['get_google_service_account'] + + @property + def create_transfer_job(self) -> Callable[ + [transfer.CreateTransferJobRequest], + Awaitable[transfer_types.TransferJob]]: + r"""Return a callable for the create transfer job method over gRPC. + + Creates a transfer job that runs periodically. + + Returns: + Callable[[~.CreateTransferJobRequest], + Awaitable[~.TransferJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['create_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/CreateTransferJob', + request_serializer=transfer.CreateTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['create_transfer_job'] + + @property + def update_transfer_job(self) -> Callable[ + [transfer.UpdateTransferJobRequest], + Awaitable[transfer_types.TransferJob]]: + r"""Return a callable for the update transfer job method over gRPC. + + Updates a transfer job. Updating a job's transfer spec does not + affect transfer operations that are running already. + + **Note:** The job's + [status][google.storagetransfer.v1.TransferJob.status] field can + be modified using this RPC (for example, to set a job's status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED], + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + or + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED]). + + Returns: + Callable[[~.UpdateTransferJobRequest], + Awaitable[~.TransferJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['update_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/UpdateTransferJob', + request_serializer=transfer.UpdateTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['update_transfer_job'] + + @property + def get_transfer_job(self) -> Callable[ + [transfer.GetTransferJobRequest], + Awaitable[transfer_types.TransferJob]]: + r"""Return a callable for the get transfer job method over gRPC. + + Gets a transfer job. + + Returns: + Callable[[~.GetTransferJobRequest], + Awaitable[~.TransferJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_job' not in self._stubs: + self._stubs['get_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetTransferJob', + request_serializer=transfer.GetTransferJobRequest.serialize, + response_deserializer=transfer_types.TransferJob.deserialize, + ) + return self._stubs['get_transfer_job'] + + @property + def list_transfer_jobs(self) -> Callable[ + [transfer.ListTransferJobsRequest], + Awaitable[transfer.ListTransferJobsResponse]]: + r"""Return a callable for the list transfer jobs method over gRPC. + + Lists transfer jobs. + + Returns: + Callable[[~.ListTransferJobsRequest], + Awaitable[~.ListTransferJobsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transfer_jobs' not in self._stubs: + self._stubs['list_transfer_jobs'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ListTransferJobs', + request_serializer=transfer.ListTransferJobsRequest.serialize, + response_deserializer=transfer.ListTransferJobsResponse.deserialize, + ) + return self._stubs['list_transfer_jobs'] + + @property + def pause_transfer_operation(self) -> Callable[ + [transfer.PauseTransferOperationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the pause transfer operation method over gRPC. + + Pauses a transfer operation. + + Returns: + Callable[[~.PauseTransferOperationRequest], + 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 'pause_transfer_operation' not in self._stubs: + self._stubs['pause_transfer_operation'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/PauseTransferOperation', + request_serializer=transfer.PauseTransferOperationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['pause_transfer_operation'] + + @property + def resume_transfer_operation(self) -> Callable[ + [transfer.ResumeTransferOperationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the resume transfer operation method over gRPC. + + Resumes a transfer operation that is paused. + + Returns: + Callable[[~.ResumeTransferOperationRequest], + 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 'resume_transfer_operation' not in self._stubs: + self._stubs['resume_transfer_operation'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ResumeTransferOperation', + request_serializer=transfer.ResumeTransferOperationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['resume_transfer_operation'] + + @property + def run_transfer_job(self) -> Callable[ + [transfer.RunTransferJobRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run transfer job method over gRPC. + + Starts a new operation for the specified transfer job. A + ``TransferJob`` has a maximum of one active + ``TransferOperation``. If this method is called while a + ``TransferOperation`` is active, an error is returned. + + Returns: + Callable[[~.RunTransferJobRequest], + 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 'run_transfer_job' not in self._stubs: + self._stubs['run_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/RunTransferJob', + request_serializer=transfer.RunTransferJobRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_transfer_job'] + + @property + def delete_transfer_job(self) -> Callable[ + [transfer.DeleteTransferJobRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transfer job method over gRPC. + + Deletes a transfer job. Deleting a transfer job sets its status + to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED]. + + Returns: + Callable[[~.DeleteTransferJobRequest], + 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_transfer_job' not in self._stubs: + self._stubs['delete_transfer_job'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/DeleteTransferJob', + request_serializer=transfer.DeleteTransferJobRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_job'] + + @property + def create_agent_pool(self) -> Callable[ + [transfer.CreateAgentPoolRequest], + Awaitable[transfer_types.AgentPool]]: + r"""Return a callable for the create agent pool method over gRPC. + + Creates an agent pool resource. + + Returns: + Callable[[~.CreateAgentPoolRequest], + Awaitable[~.AgentPool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['create_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/CreateAgentPool', + request_serializer=transfer.CreateAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['create_agent_pool'] + + @property + def update_agent_pool(self) -> Callable[ + [transfer.UpdateAgentPoolRequest], + Awaitable[transfer_types.AgentPool]]: + r"""Return a callable for the update agent pool method over gRPC. + + Updates an existing agent pool resource. + + Returns: + Callable[[~.UpdateAgentPoolRequest], + Awaitable[~.AgentPool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['update_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/UpdateAgentPool', + request_serializer=transfer.UpdateAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['update_agent_pool'] + + @property + def get_agent_pool(self) -> Callable[ + [transfer.GetAgentPoolRequest], + Awaitable[transfer_types.AgentPool]]: + r"""Return a callable for the get agent pool method over gRPC. + + Gets an agent pool. + + Returns: + Callable[[~.GetAgentPoolRequest], + Awaitable[~.AgentPool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pool' not in self._stubs: + self._stubs['get_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/GetAgentPool', + request_serializer=transfer.GetAgentPoolRequest.serialize, + response_deserializer=transfer_types.AgentPool.deserialize, + ) + return self._stubs['get_agent_pool'] + + @property + def list_agent_pools(self) -> Callable[ + [transfer.ListAgentPoolsRequest], + Awaitable[transfer.ListAgentPoolsResponse]]: + r"""Return a callable for the list agent pools method over gRPC. + + Lists agent pools. + + Returns: + Callable[[~.ListAgentPoolsRequest], + Awaitable[~.ListAgentPoolsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_pools' not in self._stubs: + self._stubs['list_agent_pools'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/ListAgentPools', + request_serializer=transfer.ListAgentPoolsRequest.serialize, + response_deserializer=transfer.ListAgentPoolsResponse.deserialize, + ) + return self._stubs['list_agent_pools'] + + @property + def delete_agent_pool(self) -> Callable[ + [transfer.DeleteAgentPoolRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete agent pool method over gRPC. + + Deletes an agent pool. + + Returns: + Callable[[~.DeleteAgentPoolRequest], + 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_agent_pool' not in self._stubs: + self._stubs['delete_agent_pool'] = self.grpc_channel.unary_unary( + '/google.storagetransfer.v1.StorageTransferService/DeleteAgentPool', + request_serializer=transfer.DeleteAgentPoolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent_pool'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_google_service_account: gapic_v1.method_async.wrap_method( + self.get_google_service_account, + default_timeout=None, + client_info=client_info, + ), + self.create_transfer_job: gapic_v1.method_async.wrap_method( + self.create_transfer_job, + default_timeout=60.0, + client_info=client_info, + ), + self.update_transfer_job: gapic_v1.method_async.wrap_method( + self.update_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.get_transfer_job: gapic_v1.method_async.wrap_method( + self.get_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.list_transfer_jobs: gapic_v1.method_async.wrap_method( + self.list_transfer_jobs, + default_timeout=None, + client_info=client_info, + ), + self.pause_transfer_operation: gapic_v1.method_async.wrap_method( + self.pause_transfer_operation, + default_timeout=None, + client_info=client_info, + ), + self.resume_transfer_operation: gapic_v1.method_async.wrap_method( + self.resume_transfer_operation, + default_timeout=None, + client_info=client_info, + ), + self.run_transfer_job: gapic_v1.method_async.wrap_method( + self.run_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.delete_transfer_job: gapic_v1.method_async.wrap_method( + self.delete_transfer_job, + default_timeout=None, + client_info=client_info, + ), + self.create_agent_pool: gapic_v1.method_async.wrap_method( + self.create_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.update_agent_pool: gapic_v1.method_async.wrap_method( + self.update_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_pool: gapic_v1.method_async.wrap_method( + self.get_agent_pool, + default_timeout=None, + client_info=client_info, + ), + self.list_agent_pools: gapic_v1.method_async.wrap_method( + self.list_agent_pools, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent_pool: gapic_v1.method_async.wrap_method( + self.delete_agent_pool, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @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"] + + +__all__ = ( + 'StorageTransferServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/rest.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/rest.py new file mode 100644 index 000000000000..c7acddc279dc --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/services/storage_transfer_service/transports/rest.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import StorageTransferServiceTransport, 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 StorageTransferServiceRestInterceptor: + """Interceptor for StorageTransferService. + + 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 StorageTransferServiceRestTransport. + + .. code-block:: python + class MyCustomStorageTransferServiceInterceptor(StorageTransferServiceRestInterceptor): + def pre_create_agent_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_agent_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_transfer_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_transfer_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_agent_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_transfer_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_agent_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_agent_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_google_service_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_google_service_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_transfer_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_transfer_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_agent_pools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_agent_pools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_transfer_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_transfer_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_pause_transfer_operation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_resume_transfer_operation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_run_transfer_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_transfer_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_agent_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_agent_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_transfer_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_transfer_job(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StorageTransferServiceRestTransport(interceptor=MyCustomStorageTransferServiceInterceptor()) + client = StorageTransferServiceClient(transport=transport) + + + """ + def pre_create_agent_pool(self, request: transfer.CreateAgentPoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.CreateAgentPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_agent_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_create_agent_pool(self, response: transfer_types.AgentPool) -> transfer_types.AgentPool: + """Post-rpc interceptor for create_agent_pool + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_create_transfer_job(self, request: transfer.CreateTransferJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.CreateTransferJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_transfer_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_create_transfer_job(self, response: transfer_types.TransferJob) -> transfer_types.TransferJob: + """Post-rpc interceptor for create_transfer_job + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_delete_agent_pool(self, request: transfer.DeleteAgentPoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.DeleteAgentPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_agent_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def pre_delete_transfer_job(self, request: transfer.DeleteTransferJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.DeleteTransferJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_transfer_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def pre_get_agent_pool(self, request: transfer.GetAgentPoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.GetAgentPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_agent_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_get_agent_pool(self, response: transfer_types.AgentPool) -> transfer_types.AgentPool: + """Post-rpc interceptor for get_agent_pool + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_get_google_service_account(self, request: transfer.GetGoogleServiceAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.GetGoogleServiceAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_service_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_get_google_service_account(self, response: transfer_types.GoogleServiceAccount) -> transfer_types.GoogleServiceAccount: + """Post-rpc interceptor for get_google_service_account + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_get_transfer_job(self, request: transfer.GetTransferJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.GetTransferJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_transfer_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_get_transfer_job(self, response: transfer_types.TransferJob) -> transfer_types.TransferJob: + """Post-rpc interceptor for get_transfer_job + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_list_agent_pools(self, request: transfer.ListAgentPoolsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.ListAgentPoolsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_agent_pools + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_list_agent_pools(self, response: transfer.ListAgentPoolsResponse) -> transfer.ListAgentPoolsResponse: + """Post-rpc interceptor for list_agent_pools + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_list_transfer_jobs(self, request: transfer.ListTransferJobsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.ListTransferJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_transfer_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_list_transfer_jobs(self, response: transfer.ListTransferJobsResponse) -> transfer.ListTransferJobsResponse: + """Post-rpc interceptor for list_transfer_jobs + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_pause_transfer_operation(self, request: transfer.PauseTransferOperationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.PauseTransferOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for pause_transfer_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def pre_resume_transfer_operation(self, request: transfer.ResumeTransferOperationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.ResumeTransferOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for resume_transfer_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def pre_run_transfer_job(self, request: transfer.RunTransferJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.RunTransferJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_transfer_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_run_transfer_job(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_transfer_job + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_update_agent_pool(self, request: transfer.UpdateAgentPoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.UpdateAgentPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_agent_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_update_agent_pool(self, response: transfer_types.AgentPool) -> transfer_types.AgentPool: + """Post-rpc interceptor for update_agent_pool + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService server but before + it is returned to user code. + """ + return response + def pre_update_transfer_job(self, request: transfer.UpdateTransferJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[transfer.UpdateTransferJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_transfer_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageTransferService server. + """ + return request, metadata + + def post_update_transfer_job(self, response: transfer_types.TransferJob) -> transfer_types.TransferJob: + """Post-rpc interceptor for update_transfer_job + + Override in a subclass to manipulate the response + after it is returned by the StorageTransferService 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 StorageTransferService 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 StorageTransferService 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 StorageTransferService 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 StorageTransferService 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 StorageTransferService 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 StorageTransferService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class StorageTransferServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StorageTransferServiceRestInterceptor + + +class StorageTransferServiceRestTransport(StorageTransferServiceTransport): + """REST backend transport for StorageTransferService. + + Storage Transfer Service and its protos. + Transfers data between between Google Cloud Storage buckets or + from a data source external to Google to a Cloud Storage bucket. + + 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 = 'storagetransfer.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[StorageTransferServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storagetransfer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + 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 StorageTransferServiceRestInterceptor() + 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=transferOperations/**}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=transferOperations/**}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=transferOperations}', + }, + ], + } + + 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 _CreateAgentPool(StorageTransferServiceRestStub): + def __hash__(self): + return hash("CreateAgentPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "agentPoolId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.CreateAgentPoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.AgentPool: + r"""Call the create agent pool method over HTTP. + + Args: + request (~.transfer.CreateAgentPoolRequest): + The request object. Specifies the request passed to + CreateAgentPool. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.AgentPool: + Represents an agent pool. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/projects/{project_id=*}/agentPools', + 'body': 'agent_pool', + }, + ] + request, metadata = self._interceptor.pre_create_agent_pool(request, metadata) + pb_request = transfer.CreateAgentPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.AgentPool() + pb_resp = transfer_types.AgentPool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_agent_pool(resp) + return resp + + class _CreateTransferJob(StorageTransferServiceRestStub): + def __hash__(self): + return hash("CreateTransferJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.CreateTransferJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.TransferJob: + r"""Call the create transfer job method over HTTP. + + Args: + request (~.transfer.CreateTransferJobRequest): + The request object. Request passed to CreateTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/transferJobs', + 'body': 'transfer_job', + }, + ] + request, metadata = self._interceptor.pre_create_transfer_job(request, metadata) + pb_request = transfer.CreateTransferJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.TransferJob() + pb_resp = transfer_types.TransferJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_transfer_job(resp) + return resp + + class _DeleteAgentPool(StorageTransferServiceRestStub): + def __hash__(self): + return hash("DeleteAgentPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.DeleteAgentPoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete agent pool method over HTTP. + + Args: + request (~.transfer.DeleteAgentPoolRequest): + The request object. Specifies the request passed to + DeleteAgentPool. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/*/agentPools/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_agent_pool(request, metadata) + pb_request = transfer.DeleteAgentPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteTransferJob(StorageTransferServiceRestStub): + def __hash__(self): + return hash("DeleteTransferJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "projectId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.DeleteTransferJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete transfer job method over HTTP. + + Args: + request (~.transfer.DeleteTransferJobRequest): + The request object. Request passed to DeleteTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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/{job_name=transferJobs/**}', + }, + ] + request, metadata = self._interceptor.pre_delete_transfer_job(request, metadata) + pb_request = transfer.DeleteTransferJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetAgentPool(StorageTransferServiceRestStub): + def __hash__(self): + return hash("GetAgentPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.GetAgentPoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.AgentPool: + r"""Call the get agent pool method over HTTP. + + Args: + request (~.transfer.GetAgentPoolRequest): + The request object. Specifies the request passed to + GetAgentPool. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.AgentPool: + Represents an agent pool. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/agentPools/*}', + }, + ] + request, metadata = self._interceptor.pre_get_agent_pool(request, metadata) + pb_request = transfer.GetAgentPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.AgentPool() + pb_resp = transfer_types.AgentPool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_agent_pool(resp) + return resp + + class _GetGoogleServiceAccount(StorageTransferServiceRestStub): + def __hash__(self): + return hash("GetGoogleServiceAccount") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.GetGoogleServiceAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.GoogleServiceAccount: + r"""Call the get google service + account method over HTTP. + + Args: + request (~.transfer.GetGoogleServiceAccountRequest): + The request object. Request passed to + GetGoogleServiceAccount. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.GoogleServiceAccount: + Google service account + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/googleServiceAccounts/{project_id}', + }, + ] + request, metadata = self._interceptor.pre_get_google_service_account(request, metadata) + pb_request = transfer.GetGoogleServiceAccountRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.GoogleServiceAccount() + pb_resp = transfer_types.GoogleServiceAccount.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_service_account(resp) + return resp + + class _GetTransferJob(StorageTransferServiceRestStub): + def __hash__(self): + return hash("GetTransferJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "projectId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.GetTransferJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.TransferJob: + r"""Call the get transfer job method over HTTP. + + Args: + request (~.transfer.GetTransferJobRequest): + The request object. Request passed to GetTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{job_name=transferJobs/**}', + }, + ] + request, metadata = self._interceptor.pre_get_transfer_job(request, metadata) + pb_request = transfer.GetTransferJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.TransferJob() + pb_resp = transfer_types.TransferJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_transfer_job(resp) + return resp + + class _ListAgentPools(StorageTransferServiceRestStub): + def __hash__(self): + return hash("ListAgentPools") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.ListAgentPoolsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer.ListAgentPoolsResponse: + r"""Call the list agent pools method over HTTP. + + Args: + request (~.transfer.ListAgentPoolsRequest): + The request object. The request passed to ListAgentPools. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer.ListAgentPoolsResponse: + Response from ListAgentPools. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/projects/{project_id=*}/agentPools', + }, + ] + request, metadata = self._interceptor.pre_list_agent_pools(request, metadata) + pb_request = transfer.ListAgentPoolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer.ListAgentPoolsResponse() + pb_resp = transfer.ListAgentPoolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_agent_pools(resp) + return resp + + class _ListTransferJobs(StorageTransferServiceRestStub): + def __hash__(self): + return hash("ListTransferJobs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "filter" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.ListTransferJobsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer.ListTransferJobsResponse: + r"""Call the list transfer jobs method over HTTP. + + Args: + request (~.transfer.ListTransferJobsRequest): + The request object. ``projectId``, ``jobNames``, and ``jobStatuses`` are + query parameters that can be specified when listing + transfer jobs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer.ListTransferJobsResponse: + Response from ListTransferJobs. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/transferJobs', + }, + ] + request, metadata = self._interceptor.pre_list_transfer_jobs(request, metadata) + pb_request = transfer.ListTransferJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer.ListTransferJobsResponse() + pb_resp = transfer.ListTransferJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_transfer_jobs(resp) + return resp + + class _PauseTransferOperation(StorageTransferServiceRestStub): + def __hash__(self): + return hash("PauseTransferOperation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.PauseTransferOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the pause transfer operation method over HTTP. + + Args: + request (~.transfer.PauseTransferOperationRequest): + The request object. Request passed to + PauseTransferOperation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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=transferOperations/**}:pause', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_pause_transfer_operation(request, metadata) + pb_request = transfer.PauseTransferOperationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ResumeTransferOperation(StorageTransferServiceRestStub): + def __hash__(self): + return hash("ResumeTransferOperation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.ResumeTransferOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the resume transfer operation method over HTTP. + + Args: + request (~.transfer.ResumeTransferOperationRequest): + The request object. Request passed to + ResumeTransferOperation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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=transferOperations/**}:resume', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_resume_transfer_operation(request, metadata) + pb_request = transfer.ResumeTransferOperationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _RunTransferJob(StorageTransferServiceRestStub): + def __hash__(self): + return hash("RunTransferJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.RunTransferJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run transfer job method over HTTP. + + Args: + request (~.transfer.RunTransferJobRequest): + The request object. Request passed to RunTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{job_name=transferJobs/**}:run', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_transfer_job(request, metadata) + pb_request = transfer.RunTransferJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_transfer_job(resp) + return resp + + class _UpdateAgentPool(StorageTransferServiceRestStub): + def __hash__(self): + return hash("UpdateAgentPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.UpdateAgentPoolRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.AgentPool: + r"""Call the update agent pool method over HTTP. + + Args: + request (~.transfer.UpdateAgentPoolRequest): + The request object. Specifies the request passed to + UpdateAgentPool. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.AgentPool: + Represents an agent pool. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{agent_pool.name=projects/*/agentPools/*}', + 'body': 'agent_pool', + }, + ] + request, metadata = self._interceptor.pre_update_agent_pool(request, metadata) + pb_request = transfer.UpdateAgentPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.AgentPool() + pb_resp = transfer_types.AgentPool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_agent_pool(resp) + return resp + + class _UpdateTransferJob(StorageTransferServiceRestStub): + def __hash__(self): + return hash("UpdateTransferJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: transfer.UpdateTransferJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> transfer_types.TransferJob: + r"""Call the update transfer job method over HTTP. + + Args: + request (~.transfer.UpdateTransferJobRequest): + The request object. Request passed to UpdateTransferJob. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.transfer_types.TransferJob: + This resource represents the + configuration of a transfer job that + runs periodically. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{job_name=transferJobs/**}', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_transfer_job(request, metadata) + pb_request = transfer.UpdateTransferJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = transfer_types.TransferJob() + pb_resp = transfer_types.TransferJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_transfer_job(resp) + return resp + + @property + def create_agent_pool(self) -> Callable[ + [transfer.CreateAgentPoolRequest], + transfer_types.AgentPool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAgentPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_transfer_job(self) -> Callable[ + [transfer.CreateTransferJobRequest], + transfer_types.TransferJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTransferJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_agent_pool(self) -> Callable[ + [transfer.DeleteAgentPoolRequest], + 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._DeleteAgentPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_transfer_job(self) -> Callable[ + [transfer.DeleteTransferJobRequest], + 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._DeleteTransferJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_agent_pool(self) -> Callable[ + [transfer.GetAgentPoolRequest], + transfer_types.AgentPool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAgentPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_google_service_account(self) -> Callable[ + [transfer.GetGoogleServiceAccountRequest], + transfer_types.GoogleServiceAccount]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetGoogleServiceAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_transfer_job(self) -> Callable[ + [transfer.GetTransferJobRequest], + transfer_types.TransferJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTransferJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_agent_pools(self) -> Callable[ + [transfer.ListAgentPoolsRequest], + transfer.ListAgentPoolsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAgentPools(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_transfer_jobs(self) -> Callable[ + [transfer.ListTransferJobsRequest], + transfer.ListTransferJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTransferJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def pause_transfer_operation(self) -> Callable[ + [transfer.PauseTransferOperationRequest], + 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._PauseTransferOperation(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume_transfer_operation(self) -> Callable[ + [transfer.ResumeTransferOperationRequest], + 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._ResumeTransferOperation(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_transfer_job(self) -> Callable[ + [transfer.RunTransferJobRequest], + 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._RunTransferJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_agent_pool(self) -> Callable[ + [transfer.UpdateAgentPoolRequest], + transfer_types.AgentPool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAgentPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_transfer_job(self) -> Callable[ + [transfer.UpdateTransferJobRequest], + transfer_types.TransferJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTransferJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(StorageTransferServiceRestStub): + 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=transferOperations/**}: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 get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(StorageTransferServiceRestStub): + 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=transferOperations/**}', + }, + ] + + 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(StorageTransferServiceRestStub): + 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=transferOperations}', + }, + ] + + 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__=( + 'StorageTransferServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/__init__.py new file mode 100644 index 000000000000..d95a3bc8743b --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/__init__.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .transfer import ( + CreateAgentPoolRequest, + CreateTransferJobRequest, + DeleteAgentPoolRequest, + DeleteTransferJobRequest, + GetAgentPoolRequest, + GetGoogleServiceAccountRequest, + GetTransferJobRequest, + ListAgentPoolsRequest, + ListAgentPoolsResponse, + ListTransferJobsRequest, + ListTransferJobsResponse, + PauseTransferOperationRequest, + ResumeTransferOperationRequest, + RunTransferJobRequest, + UpdateAgentPoolRequest, + UpdateTransferJobRequest, +) +from .transfer_types import ( + AgentPool, + AwsAccessKey, + AwsS3CompatibleData, + AwsS3Data, + AzureBlobStorageData, + AzureCredentials, + ErrorLogEntry, + ErrorSummary, + EventStream, + GcsData, + GoogleServiceAccount, + HdfsData, + HttpData, + LoggingConfig, + MetadataOptions, + NotificationConfig, + ObjectConditions, + PosixFilesystem, + S3CompatibleMetadata, + Schedule, + TransferCounters, + TransferJob, + TransferManifest, + TransferOperation, + TransferOptions, + TransferSpec, +) + +__all__ = ( + 'CreateAgentPoolRequest', + 'CreateTransferJobRequest', + 'DeleteAgentPoolRequest', + 'DeleteTransferJobRequest', + 'GetAgentPoolRequest', + 'GetGoogleServiceAccountRequest', + 'GetTransferJobRequest', + 'ListAgentPoolsRequest', + 'ListAgentPoolsResponse', + 'ListTransferJobsRequest', + 'ListTransferJobsResponse', + 'PauseTransferOperationRequest', + 'ResumeTransferOperationRequest', + 'RunTransferJobRequest', + 'UpdateAgentPoolRequest', + 'UpdateTransferJobRequest', + 'AgentPool', + 'AwsAccessKey', + 'AwsS3CompatibleData', + 'AwsS3Data', + 'AzureBlobStorageData', + 'AzureCredentials', + 'ErrorLogEntry', + 'ErrorSummary', + 'EventStream', + 'GcsData', + 'GoogleServiceAccount', + 'HdfsData', + 'HttpData', + 'LoggingConfig', + 'MetadataOptions', + 'NotificationConfig', + 'ObjectConditions', + 'PosixFilesystem', + 'S3CompatibleMetadata', + 'Schedule', + 'TransferCounters', + 'TransferJob', + 'TransferManifest', + 'TransferOperation', + 'TransferOptions', + 'TransferSpec', +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer.py new file mode 100644 index 000000000000..619818d8cdce --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.storage_transfer_v1.types import transfer_types +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.storagetransfer.v1', + manifest={ + 'GetGoogleServiceAccountRequest', + 'CreateTransferJobRequest', + 'UpdateTransferJobRequest', + 'GetTransferJobRequest', + 'DeleteTransferJobRequest', + 'ListTransferJobsRequest', + 'ListTransferJobsResponse', + 'PauseTransferOperationRequest', + 'ResumeTransferOperationRequest', + 'RunTransferJobRequest', + 'CreateAgentPoolRequest', + 'UpdateAgentPoolRequest', + 'GetAgentPoolRequest', + 'DeleteAgentPoolRequest', + 'ListAgentPoolsRequest', + 'ListAgentPoolsResponse', + }, +) + + +class GetGoogleServiceAccountRequest(proto.Message): + r"""Request passed to GetGoogleServiceAccount. + + Attributes: + project_id (str): + Required. The ID of the Google Cloud project + that the Google service account is associated + with. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTransferJobRequest(proto.Message): + r"""Request passed to CreateTransferJob. + + Attributes: + transfer_job (google.cloud.storage_transfer_v1.types.TransferJob): + Required. The job to create. + """ + + transfer_job: transfer_types.TransferJob = proto.Field( + proto.MESSAGE, + number=1, + message=transfer_types.TransferJob, + ) + + +class UpdateTransferJobRequest(proto.Message): + r"""Request passed to UpdateTransferJob. + + Attributes: + job_name (str): + Required. The name of job to update. + project_id (str): + Required. The ID of the Google Cloud project + that owns the job. + transfer_job (google.cloud.storage_transfer_v1.types.TransferJob): + Required. The job to update. ``transferJob`` is expected to + specify one or more of five fields: + [description][google.storagetransfer.v1.TransferJob.description], + [transfer_spec][google.storagetransfer.v1.TransferJob.transfer_spec], + [notification_config][google.storagetransfer.v1.TransferJob.notification_config], + [logging_config][google.storagetransfer.v1.TransferJob.logging_config], + and [status][google.storagetransfer.v1.TransferJob.status]. + An ``UpdateTransferJobRequest`` that specifies other fields + are rejected with the error + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + Updating a job status to + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED] + requires ``storagetransfer.jobs.delete`` permission. + update_transfer_job_field_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask of the fields in ``transferJob`` that are to + be updated in this request. Fields in ``transferJob`` that + can be updated are: + [description][google.storagetransfer.v1.TransferJob.description], + [transfer_spec][google.storagetransfer.v1.TransferJob.transfer_spec], + [notification_config][google.storagetransfer.v1.TransferJob.notification_config], + [logging_config][google.storagetransfer.v1.TransferJob.logging_config], + and [status][google.storagetransfer.v1.TransferJob.status]. + To update the ``transfer_spec`` of the job, a complete + transfer specification must be provided. An incomplete + specification missing any required fields is rejected with + the error + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + """ + + job_name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + transfer_job: transfer_types.TransferJob = proto.Field( + proto.MESSAGE, + number=3, + message=transfer_types.TransferJob, + ) + update_transfer_job_field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class GetTransferJobRequest(proto.Message): + r"""Request passed to GetTransferJob. + + Attributes: + job_name (str): + Required. The job to get. + project_id (str): + Required. The ID of the Google Cloud project + that owns the job. + """ + + job_name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteTransferJobRequest(proto.Message): + r"""Request passed to DeleteTransferJob. + + Attributes: + job_name (str): + Required. The job to delete. + project_id (str): + Required. The ID of the Google Cloud project + that owns the job. + """ + + job_name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListTransferJobsRequest(proto.Message): + r"""``projectId``, ``jobNames``, and ``jobStatuses`` are query + parameters that can be specified when listing transfer jobs. + + Attributes: + filter (str): + Required. A list of query parameters specified as JSON text + in the form of: + ``{"projectId":"my_project_id", "jobNames":["jobid1","jobid2",...], "jobStatuses":["status1","status2",...]}`` + + Since ``jobNames`` and ``jobStatuses`` support multiple + values, their values must be specified with array notation. + ``projectId`` is required. ``jobNames`` and ``jobStatuses`` + are optional. The valid values for ``jobStatuses`` are + case-insensitive: + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED], + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + and + [DELETED][google.storagetransfer.v1.TransferJob.Status.DELETED]. + page_size (int): + The list page size. The max allowed value is + 256. + page_token (str): + The list page token. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListTransferJobsResponse(proto.Message): + r"""Response from ListTransferJobs. + + Attributes: + transfer_jobs (MutableSequence[google.cloud.storage_transfer_v1.types.TransferJob]): + A list of transfer jobs. + next_page_token (str): + The list next page token. + """ + + @property + def raw_page(self): + return self + + transfer_jobs: MutableSequence[transfer_types.TransferJob] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer_types.TransferJob, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PauseTransferOperationRequest(proto.Message): + r"""Request passed to PauseTransferOperation. + + Attributes: + name (str): + Required. The name of the transfer operation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ResumeTransferOperationRequest(proto.Message): + r"""Request passed to ResumeTransferOperation. + + Attributes: + name (str): + Required. The name of the transfer operation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RunTransferJobRequest(proto.Message): + r"""Request passed to RunTransferJob. + + Attributes: + job_name (str): + Required. The name of the transfer job. + project_id (str): + Required. The ID of the Google Cloud project + that owns the transfer job. + """ + + job_name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAgentPoolRequest(proto.Message): + r"""Specifies the request passed to CreateAgentPool. + + Attributes: + project_id (str): + Required. The ID of the Google Cloud project + that owns the agent pool. + agent_pool (google.cloud.storage_transfer_v1.types.AgentPool): + Required. The agent pool to create. + agent_pool_id (str): + Required. The ID of the agent pool to create. + + The ``agent_pool_id`` must meet the following requirements: + + - Length of 128 characters or less. + - Not start with the string ``goog``. + - Start with a lowercase ASCII character, followed by: + + - Zero or more: lowercase Latin alphabet characters, + numerals, hyphens (``-``), periods (``.``), + underscores (``_``), or tildes (``~``). + - One or more numerals or lowercase ASCII characters. + + As expressed by the regular expression: + ``^(?!goog)[a-z]([a-z0-9-._~]*[a-z0-9])?$``. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + agent_pool: transfer_types.AgentPool = proto.Field( + proto.MESSAGE, + number=2, + message=transfer_types.AgentPool, + ) + agent_pool_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateAgentPoolRequest(proto.Message): + r"""Specifies the request passed to UpdateAgentPool. + + Attributes: + agent_pool (google.cloud.storage_transfer_v1.types.AgentPool): + Required. The agent pool to update. ``agent_pool`` is + expected to specify following fields: + + - [name][google.storagetransfer.v1.AgentPool.name] + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + An ``UpdateAgentPoolRequest`` with any other fields is + rejected with the error + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The [field mask] + (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf) + of the fields in ``agentPool`` to update in this request. + The following ``agentPool`` fields can be updated: + + - [display_name][google.storagetransfer.v1.AgentPool.display_name] + + - [bandwidth_limit][google.storagetransfer.v1.AgentPool.bandwidth_limit] + """ + + agent_pool: transfer_types.AgentPool = proto.Field( + proto.MESSAGE, + number=1, + message=transfer_types.AgentPool, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAgentPoolRequest(proto.Message): + r"""Specifies the request passed to GetAgentPool. + + Attributes: + name (str): + Required. The name of the agent pool to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteAgentPoolRequest(proto.Message): + r"""Specifies the request passed to DeleteAgentPool. + + Attributes: + name (str): + Required. The name of the agent pool to + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAgentPoolsRequest(proto.Message): + r"""The request passed to ListAgentPools. + + Attributes: + project_id (str): + Required. The ID of the Google Cloud project + that owns the job. + filter (str): + An optional list of query parameters specified as JSON text + in the form of: + + ``{"agentPoolNames":["agentpool1","agentpool2",...]}`` + + Since ``agentPoolNames`` support multiple values, its values + must be specified with array notation. When the filter is + either empty or not provided, the list returns all agent + pools for the project. + page_size (int): + The list page size. The max allowed value is ``256``. + page_token (str): + The list page token. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAgentPoolsResponse(proto.Message): + r"""Response from ListAgentPools. + + Attributes: + agent_pools (MutableSequence[google.cloud.storage_transfer_v1.types.AgentPool]): + A list of agent pools. + next_page_token (str): + The list next page token. + """ + + @property + def raw_page(self): + return self + + agent_pools: MutableSequence[transfer_types.AgentPool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer_types.AgentPool, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer_types.py b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer_types.py new file mode 100644 index 000000000000..5c459e9d3aac --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/google/cloud/storage_transfer_v1/types/transfer_types.py @@ -0,0 +1,2255 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.storagetransfer.v1', + manifest={ + 'GoogleServiceAccount', + 'AwsAccessKey', + 'AzureCredentials', + 'ObjectConditions', + 'GcsData', + 'AwsS3Data', + 'AzureBlobStorageData', + 'HttpData', + 'PosixFilesystem', + 'HdfsData', + 'AwsS3CompatibleData', + 'S3CompatibleMetadata', + 'AgentPool', + 'TransferOptions', + 'TransferSpec', + 'MetadataOptions', + 'TransferManifest', + 'Schedule', + 'EventStream', + 'TransferJob', + 'ErrorLogEntry', + 'ErrorSummary', + 'TransferCounters', + 'NotificationConfig', + 'LoggingConfig', + 'TransferOperation', + }, +) + + +class GoogleServiceAccount(proto.Message): + r"""Google service account + + Attributes: + account_email (str): + Email address of the service account. + subject_id (str): + Unique identifier for the service account. + """ + + account_email: str = proto.Field( + proto.STRING, + number=1, + ) + subject_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AwsAccessKey(proto.Message): + r"""AWS access key (see `AWS Security + Credentials `__). + + For information on our data retention policy for user credentials, + see `User + credentials `__. + + Attributes: + access_key_id (str): + Required. AWS access key ID. + secret_access_key (str): + Required. AWS secret access key. This field + is not returned in RPC responses. + """ + + access_key_id: str = proto.Field( + proto.STRING, + number=1, + ) + secret_access_key: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AzureCredentials(proto.Message): + r"""Azure credentials + + For information on our data retention policy for user credentials, + see `User + credentials `__. + + Attributes: + sas_token (str): + Required. Azure shared access signature (SAS). + + For more information about SAS, see `Grant limited access to + Azure Storage resources using shared access signatures + (SAS) `__. + """ + + sas_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ObjectConditions(proto.Message): + r"""Conditions that determine which objects are transferred. Applies + only to Cloud Data Sources such as S3, Azure, and Cloud Storage. + + The "last modification time" refers to the time of the last change + to the object's content or metadata — specifically, this is the + ``updated`` property of Cloud Storage objects, the ``LastModified`` + field of S3 objects, and the ``Last-Modified`` header of Azure + blobs. + + Transfers with a + [PosixFilesystem][google.storagetransfer.v1.PosixFilesystem] source + or destination don't support ``ObjectConditions``. + + Attributes: + min_time_elapsed_since_last_modification (google.protobuf.duration_pb2.Duration): + Ensures that objects are not transferred until a specific + minimum time has elapsed after the "last modification time". + When a + [TransferOperation][google.storagetransfer.v1.TransferOperation] + begins, objects with a "last modification time" are + transferred only if the elapsed time between the + [start_time][google.storagetransfer.v1.TransferOperation.start_time] + of the ``TransferOperation`` and the "last modification + time" of the object is equal to or greater than the value of + min_time_elapsed_since_last_modification`. Objects that do + not have a "last modification time" are also transferred. + max_time_elapsed_since_last_modification (google.protobuf.duration_pb2.Duration): + Ensures that objects are not transferred if a specific + maximum time has elapsed since the "last modification time". + When a + [TransferOperation][google.storagetransfer.v1.TransferOperation] + begins, objects with a "last modification time" are + transferred only if the elapsed time between the + [start_time][google.storagetransfer.v1.TransferOperation.start_time] + of the ``TransferOperation``\ and the "last modification + time" of the object is less than the value of + max_time_elapsed_since_last_modification`. Objects that do + not have a "last modification time" are also transferred. + include_prefixes (MutableSequence[str]): + If you specify ``include_prefixes``, Storage Transfer + Service uses the items in the ``include_prefixes`` array to + determine which objects to include in a transfer. Objects + must start with one of the matching ``include_prefixes`` for + inclusion in the transfer. If + [exclude_prefixes][google.storagetransfer.v1.ObjectConditions.exclude_prefixes] + is specified, objects must not start with any of the + ``exclude_prefixes`` specified for inclusion in the + transfer. + + The following are requirements of ``include_prefixes``: + + - Each include-prefix can contain any sequence of Unicode + characters, to a max length of 1024 bytes when + UTF8-encoded, and must not contain Carriage Return or + Line Feed characters. Wildcard matching and regular + expression matching are not supported. + + - Each include-prefix must omit the leading slash. For + example, to include the object + ``s3://my-aws-bucket/logs/y=2015/requests.gz``, specify + the include-prefix as ``logs/y=2015/requests.gz``. + + - None of the include-prefix values can be empty, if + specified. + + - Each include-prefix must include a distinct portion of + the object namespace. No include-prefix may be a prefix + of another include-prefix. + + The max size of ``include_prefixes`` is 1000. + + For more information, see `Filtering objects from + transfers `__. + exclude_prefixes (MutableSequence[str]): + If you specify ``exclude_prefixes``, Storage Transfer + Service uses the items in the ``exclude_prefixes`` array to + determine which objects to exclude from a transfer. Objects + must not start with one of the matching ``exclude_prefixes`` + for inclusion in a transfer. + + The following are requirements of ``exclude_prefixes``: + + - Each exclude-prefix can contain any sequence of Unicode + characters, to a max length of 1024 bytes when + UTF8-encoded, and must not contain Carriage Return or + Line Feed characters. Wildcard matching and regular + expression matching are not supported. + + - Each exclude-prefix must omit the leading slash. For + example, to exclude the object + ``s3://my-aws-bucket/logs/y=2015/requests.gz``, specify + the exclude-prefix as ``logs/y=2015/requests.gz``. + + - None of the exclude-prefix values can be empty, if + specified. + + - Each exclude-prefix must exclude a distinct portion of + the object namespace. No exclude-prefix may be a prefix + of another exclude-prefix. + + - If + [include_prefixes][google.storagetransfer.v1.ObjectConditions.include_prefixes] + is specified, then each exclude-prefix must start with + the value of a path explicitly included by + ``include_prefixes``. + + The max size of ``exclude_prefixes`` is 1000. + + For more information, see `Filtering objects from + transfers `__. + last_modified_since (google.protobuf.timestamp_pb2.Timestamp): + If specified, only objects with a "last modification time" + on or after this timestamp and objects that don't have a + "last modification time" are transferred. + + The ``last_modified_since`` and ``last_modified_before`` + fields can be used together for chunked data processing. For + example, consider a script that processes each day's worth + of data at a time. For that you'd set each of the fields as + follows: + + - ``last_modified_since`` to the start of the day + + - ``last_modified_before`` to the end of the day + last_modified_before (google.protobuf.timestamp_pb2.Timestamp): + If specified, only objects with a "last + modification time" before this timestamp and + objects that don't have a "last modification + time" are transferred. + """ + + min_time_elapsed_since_last_modification: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_time_elapsed_since_last_modification: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + include_prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + exclude_prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + last_modified_since: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + last_modified_before: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class GcsData(proto.Message): + r"""In a GcsData resource, an object's name is the Cloud Storage + object's name and its "last modification time" refers to the + object's ``updated`` property of Cloud Storage objects, which + changes when the content or the metadata of the object is updated. + + Attributes: + bucket_name (str): + Required. Cloud Storage bucket name. Must meet `Bucket Name + Requirements `__. + path (str): + Root path to transfer objects. + + Must be an empty string or full path name that ends with a + '/'. This field is treated as an object prefix. As such, it + should generally not begin with a '/'. + + The root path value must meet `Object Name + Requirements `__. + managed_folder_transfer_enabled (bool): + Preview. Enables the transfer of managed folders between + Cloud Storage buckets. Set this option on the + gcs_data_source. + + If set to true: + + - Managed folders in the source bucket are transferred to + the destination bucket. + - Managed folders in the destination bucket are + overwritten. Other OVERWRITE options are not supported. + + See `Transfer Cloud Storage managed + folders `__. + """ + + bucket_name: str = proto.Field( + proto.STRING, + number=1, + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + managed_folder_transfer_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class AwsS3Data(proto.Message): + r"""An AwsS3Data resource can be a data source, but not a data + sink. In an AwsS3Data resource, an object's name is the S3 + object's key name. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + bucket_name (str): + Required. S3 Bucket name (see `Creating a + bucket `__). + aws_access_key (google.cloud.storage_transfer_v1.types.AwsAccessKey): + Input only. AWS access key used to sign the API requests to + the AWS S3 bucket. Permissions on the bucket must be granted + to the access ID of the AWS access key. + + For information on our data retention policy for user + credentials, see `User + credentials `__. + path (str): + Root path to transfer objects. + + Must be an empty string or full path name that + ends with a '/'. This field is treated as an + object prefix. As such, it should generally not + begin with a '/'. + role_arn (str): + The Amazon Resource Name (ARN) of the role to support + temporary credentials via ``AssumeRoleWithWebIdentity``. For + more information about ARNs, see `IAM + ARNs `__. + + When a role ARN is provided, Transfer Service fetches + temporary credentials for the session using a + ``AssumeRoleWithWebIdentity`` call for the provided role + using the + [GoogleServiceAccount][google.storagetransfer.v1.GoogleServiceAccount] + for this project. + cloudfront_domain (str): + Optional. The CloudFront distribution domain name pointing + to this bucket, to use when fetching. + + See `Transfer from S3 via + CloudFront `__ + for more information. + + Format: ``https://{id}.cloudfront.net`` or any valid custom + domain. Must begin with ``https://``. + credentials_secret (str): + Optional. The Resource name of a secret in Secret Manager. + + AWS credentials must be stored in Secret Manager in JSON + format: + + { "access_key_id": "ACCESS_KEY_ID", "secret_access_key": + "SECRET_ACCESS_KEY" } + + [GoogleServiceAccount][google.storagetransfer.v1.GoogleServiceAccount] + must be granted ``roles/secretmanager.secretAccessor`` for + the resource. + + See [Configure access to a source: Amazon S3] + (https://cloud.google.com/storage-transfer/docs/source-amazon-s3#secret_manager) + for more information. + + If ``credentials_secret`` is specified, do not specify + [role_arn][google.storagetransfer.v1.AwsS3Data.role_arn] or + [aws_access_key][google.storagetransfer.v1.AwsS3Data.aws_access_key]. + + Format: ``projects/{project_number}/secrets/{secret_name}`` + managed_private_network (bool): + Egress bytes over a Google-managed private + network. This network is shared between other + users of Storage Transfer Service. + + This field is a member of `oneof`_ ``private_network``. + """ + + bucket_name: str = proto.Field( + proto.STRING, + number=1, + ) + aws_access_key: 'AwsAccessKey' = proto.Field( + proto.MESSAGE, + number=2, + message='AwsAccessKey', + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + role_arn: str = proto.Field( + proto.STRING, + number=4, + ) + cloudfront_domain: str = proto.Field( + proto.STRING, + number=6, + ) + credentials_secret: str = proto.Field( + proto.STRING, + number=7, + ) + managed_private_network: bool = proto.Field( + proto.BOOL, + number=8, + oneof='private_network', + ) + + +class AzureBlobStorageData(proto.Message): + r"""An AzureBlobStorageData resource can be a data source, but not a + data sink. An AzureBlobStorageData resource represents one Azure + container. The storage account determines the `Azure + endpoint `__. + In an AzureBlobStorageData resource, a blobs's name is the `Azure + Blob Storage blob's key + name `__. + + Attributes: + storage_account (str): + Required. The name of the Azure Storage + account. + azure_credentials (google.cloud.storage_transfer_v1.types.AzureCredentials): + Required. Input only. Credentials used to authenticate API + requests to Azure. + + For information on our data retention policy for user + credentials, see `User + credentials `__. + container (str): + Required. The container to transfer from the + Azure Storage account. + path (str): + Root path to transfer objects. + + Must be an empty string or full path name that + ends with a '/'. This field is treated as an + object prefix. As such, it should generally not + begin with a '/'. + credentials_secret (str): + Optional. The Resource name of a secret in Secret Manager. + + The Azure SAS token must be stored in Secret Manager in JSON + format: + + { "sas_token" : "SAS_TOKEN" } + + [GoogleServiceAccount][google.storagetransfer.v1.GoogleServiceAccount] + must be granted ``roles/secretmanager.secretAccessor`` for + the resource. + + See [Configure access to a source: Microsoft Azure Blob + Storage] + (https://cloud.google.com/storage-transfer/docs/source-microsoft-azure#secret_manager) + for more information. + + If ``credentials_secret`` is specified, do not specify + [azure_credentials][google.storagetransfer.v1.AzureBlobStorageData.azure_credentials]. + + Format: ``projects/{project_number}/secrets/{secret_name}`` + """ + + storage_account: str = proto.Field( + proto.STRING, + number=1, + ) + azure_credentials: 'AzureCredentials' = proto.Field( + proto.MESSAGE, + number=2, + message='AzureCredentials', + ) + container: str = proto.Field( + proto.STRING, + number=4, + ) + path: str = proto.Field( + proto.STRING, + number=5, + ) + credentials_secret: str = proto.Field( + proto.STRING, + number=7, + ) + + +class HttpData(proto.Message): + r"""An HttpData resource specifies a list of objects on the web to be + transferred over HTTP. The information of the objects to be + transferred is contained in a file referenced by a URL. The first + line in the file must be ``"TsvHttpData-1.0"``, which specifies the + format of the file. Subsequent lines specify the information of the + list of objects, one object per list entry. Each entry has the + following tab-delimited fields: + + - **HTTP URL** — The location of the object. + + - **Length** — The size of the object in bytes. + + - **MD5** — The base64-encoded MD5 hash of the object. + + For an example of a valid TSV file, see `Transferring data from + URLs `__. + + When transferring data based on a URL list, keep the following in + mind: + + - When an object located at ``http(s)://hostname:port/`` + is transferred to a data sink, the name of the object at the data + sink is ``/``. + + - If the specified size of an object does not match the actual size + of the object fetched, the object is not transferred. + + - If the specified MD5 does not match the MD5 computed from the + transferred bytes, the object transfer fails. + + - Ensure that each URL you specify is publicly accessible. For + example, in Cloud Storage you can [share an object publicly] + (/storage/docs/cloud-console#_sharingdata) and get a link to it. + + - Storage Transfer Service obeys ``robots.txt`` rules and requires + the source HTTP server to support ``Range`` requests and to + return a ``Content-Length`` header in each response. + + - [ObjectConditions][google.storagetransfer.v1.ObjectConditions] + have no effect when filtering objects to transfer. + + Attributes: + list_url (str): + Required. The URL that points to the file + that stores the object list entries. This file + must allow public access. Currently, only URLs + with HTTP and HTTPS schemes are supported. + """ + + list_url: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PosixFilesystem(proto.Message): + r"""A POSIX filesystem resource. + + Attributes: + root_directory (str): + Root directory path to the filesystem. + """ + + root_directory: str = proto.Field( + proto.STRING, + number=1, + ) + + +class HdfsData(proto.Message): + r"""An HdfsData resource specifies a path within an HDFS entity + (e.g. a cluster). All cluster-specific settings, such as + namenodes and ports, are configured on the transfer agents + servicing requests, so HdfsData only contains the root path to + the data in our transfer. + + Attributes: + path (str): + Root path to transfer files. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AwsS3CompatibleData(proto.Message): + r"""An AwsS3CompatibleData resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + bucket_name (str): + Required. Specifies the name of the bucket. + path (str): + Specifies the root path to transfer objects. + + Must be an empty string or full path name that + ends with a '/'. This field is treated as an + object prefix. As such, it should generally not + begin with a '/'. + endpoint (str): + Required. Specifies the endpoint of the + storage service. + region (str): + Specifies the region to sign requests with. + This can be left blank if requests should be + signed with an empty region. + s3_metadata (google.cloud.storage_transfer_v1.types.S3CompatibleMetadata): + A S3 compatible metadata. + + This field is a member of `oneof`_ ``data_provider``. + """ + + bucket_name: str = proto.Field( + proto.STRING, + number=1, + ) + path: str = proto.Field( + proto.STRING, + number=2, + ) + endpoint: str = proto.Field( + proto.STRING, + number=3, + ) + region: str = proto.Field( + proto.STRING, + number=5, + ) + s3_metadata: 'S3CompatibleMetadata' = proto.Field( + proto.MESSAGE, + number=4, + oneof='data_provider', + message='S3CompatibleMetadata', + ) + + +class S3CompatibleMetadata(proto.Message): + r"""S3CompatibleMetadata contains the metadata fields that apply + to the basic types of S3-compatible data providers. + + Attributes: + auth_method (google.cloud.storage_transfer_v1.types.S3CompatibleMetadata.AuthMethod): + Specifies the authentication and + authorization method used by the storage + service. When not specified, Transfer Service + will attempt to determine right auth method to + use. + request_model (google.cloud.storage_transfer_v1.types.S3CompatibleMetadata.RequestModel): + Specifies the API request model used to call the storage + service. When not specified, the default value of + RequestModel REQUEST_MODEL_VIRTUAL_HOSTED_STYLE is used. + protocol (google.cloud.storage_transfer_v1.types.S3CompatibleMetadata.NetworkProtocol): + Specifies the network protocol of the agent. When not + specified, the default value of NetworkProtocol + NETWORK_PROTOCOL_HTTPS is used. + list_api (google.cloud.storage_transfer_v1.types.S3CompatibleMetadata.ListApi): + The Listing API to use for discovering + objects. When not specified, Transfer Service + will attempt to determine the right API to use. + """ + class AuthMethod(proto.Enum): + r"""The authentication and authorization method used by the + storage service. + + Values: + AUTH_METHOD_UNSPECIFIED (0): + AuthMethod is not specified. + AUTH_METHOD_AWS_SIGNATURE_V4 (1): + Auth requests with AWS SigV4. + AUTH_METHOD_AWS_SIGNATURE_V2 (2): + Auth requests with AWS SigV2. + """ + AUTH_METHOD_UNSPECIFIED = 0 + AUTH_METHOD_AWS_SIGNATURE_V4 = 1 + AUTH_METHOD_AWS_SIGNATURE_V2 = 2 + + class RequestModel(proto.Enum): + r"""The request model of the API. + + Values: + REQUEST_MODEL_UNSPECIFIED (0): + RequestModel is not specified. + REQUEST_MODEL_VIRTUAL_HOSTED_STYLE (1): + Perform requests using Virtual Hosted Style. + Example: + https://bucket-name.s3.region.amazonaws.com/key-name + REQUEST_MODEL_PATH_STYLE (2): + Perform requests using Path Style. + Example: + https://s3.region.amazonaws.com/bucket-name/key-name + """ + REQUEST_MODEL_UNSPECIFIED = 0 + REQUEST_MODEL_VIRTUAL_HOSTED_STYLE = 1 + REQUEST_MODEL_PATH_STYLE = 2 + + class NetworkProtocol(proto.Enum): + r"""The agent network protocol to access the storage service. + + Values: + NETWORK_PROTOCOL_UNSPECIFIED (0): + NetworkProtocol is not specified. + NETWORK_PROTOCOL_HTTPS (1): + Perform requests using HTTPS. + NETWORK_PROTOCOL_HTTP (2): + Not recommended: This sends data in + clear-text. This is only appropriate within a + closed network or for publicly available data. + Perform requests using HTTP. + """ + NETWORK_PROTOCOL_UNSPECIFIED = 0 + NETWORK_PROTOCOL_HTTPS = 1 + NETWORK_PROTOCOL_HTTP = 2 + + class ListApi(proto.Enum): + r"""The Listing API to use for discovering objects. + + Values: + LIST_API_UNSPECIFIED (0): + ListApi is not specified. + LIST_OBJECTS_V2 (1): + Perform listing using ListObjectsV2 API. + LIST_OBJECTS (2): + Legacy ListObjects API. + """ + LIST_API_UNSPECIFIED = 0 + LIST_OBJECTS_V2 = 1 + LIST_OBJECTS = 2 + + auth_method: AuthMethod = proto.Field( + proto.ENUM, + number=1, + enum=AuthMethod, + ) + request_model: RequestModel = proto.Field( + proto.ENUM, + number=2, + enum=RequestModel, + ) + protocol: NetworkProtocol = proto.Field( + proto.ENUM, + number=3, + enum=NetworkProtocol, + ) + list_api: ListApi = proto.Field( + proto.ENUM, + number=4, + enum=ListApi, + ) + + +class AgentPool(proto.Message): + r"""Represents an agent pool. + + Attributes: + name (str): + Required. Specifies a unique string that identifies the + agent pool. + + Format: ``projects/{project_id}/agentPools/{agent_pool_id}`` + display_name (str): + Specifies the client-specified AgentPool + description. + state (google.cloud.storage_transfer_v1.types.AgentPool.State): + Output only. Specifies the state of the + AgentPool. + bandwidth_limit (google.cloud.storage_transfer_v1.types.AgentPool.BandwidthLimit): + Specifies the bandwidth limit details. If + this field is unspecified, the default value is + set as 'No Limit'. + """ + class State(proto.Enum): + r"""The state of an AgentPool. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + CREATING (1): + This is an initialization state. During this + stage, resources are allocated for the + AgentPool. + CREATED (2): + Determines that the AgentPool is created for + use. At this state, Agents can join the + AgentPool and participate in the transfer jobs + in that pool. + DELETING (3): + Determines that the AgentPool deletion has + been initiated, and all the resources are + scheduled to be cleaned up and freed. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + CREATED = 2 + DELETING = 3 + + class BandwidthLimit(proto.Message): + r"""Specifies a bandwidth limit for an agent pool. + + Attributes: + limit_mbps (int): + Bandwidth rate in megabytes per second, + distributed across all the agents in the pool. + """ + + limit_mbps: int = proto.Field( + proto.INT64, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + bandwidth_limit: BandwidthLimit = proto.Field( + proto.MESSAGE, + number=5, + message=BandwidthLimit, + ) + + +class TransferOptions(proto.Message): + r"""TransferOptions define the actions to be performed on objects + in a transfer. + + Attributes: + overwrite_objects_already_existing_in_sink (bool): + When to overwrite objects that already exist + in the sink. The default is that only objects + that are different from the source are + ovewritten. If true, all objects in the sink + whose name matches an object in the source are + overwritten with the source object. + delete_objects_unique_in_sink (bool): + Whether objects that exist only in the sink should be + deleted. + + **Note:** This option and + [delete_objects_from_source_after_transfer][google.storagetransfer.v1.TransferOptions.delete_objects_from_source_after_transfer] + are mutually exclusive. + delete_objects_from_source_after_transfer (bool): + Whether objects should be deleted from the source after they + are transferred to the sink. + + **Note:** This option and + [delete_objects_unique_in_sink][google.storagetransfer.v1.TransferOptions.delete_objects_unique_in_sink] + are mutually exclusive. + overwrite_when (google.cloud.storage_transfer_v1.types.TransferOptions.OverwriteWhen): + When to overwrite objects that already exist in the sink. If + not set, overwrite behavior is determined by + [overwrite_objects_already_existing_in_sink][google.storagetransfer.v1.TransferOptions.overwrite_objects_already_existing_in_sink]. + metadata_options (google.cloud.storage_transfer_v1.types.MetadataOptions): + Represents the selected metadata options for + a transfer job. + """ + class OverwriteWhen(proto.Enum): + r"""Specifies when to overwrite an object in the sink when an + object with matching name is found in the source. + + Values: + OVERWRITE_WHEN_UNSPECIFIED (0): + Overwrite behavior is unspecified. + DIFFERENT (1): + Overwrites destination objects with the + source objects, only if the objects have the + same name but different HTTP ETags or checksum + values. + NEVER (2): + Never overwrites a destination object if a + source object has the same name. In this case, + the source object is not transferred. + ALWAYS (3): + Always overwrite the destination object with + the source object, even if the HTTP Etags or + checksum values are the same. + """ + OVERWRITE_WHEN_UNSPECIFIED = 0 + DIFFERENT = 1 + NEVER = 2 + ALWAYS = 3 + + overwrite_objects_already_existing_in_sink: bool = proto.Field( + proto.BOOL, + number=1, + ) + delete_objects_unique_in_sink: bool = proto.Field( + proto.BOOL, + number=2, + ) + delete_objects_from_source_after_transfer: bool = proto.Field( + proto.BOOL, + number=3, + ) + overwrite_when: OverwriteWhen = proto.Field( + proto.ENUM, + number=4, + enum=OverwriteWhen, + ) + metadata_options: 'MetadataOptions' = proto.Field( + proto.MESSAGE, + number=5, + message='MetadataOptions', + ) + + +class TransferSpec(proto.Message): + r"""Configuration for running a transfer. + + 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: + gcs_data_sink (google.cloud.storage_transfer_v1.types.GcsData): + A Cloud Storage data sink. + + This field is a member of `oneof`_ ``data_sink``. + posix_data_sink (google.cloud.storage_transfer_v1.types.PosixFilesystem): + A POSIX Filesystem data sink. + + This field is a member of `oneof`_ ``data_sink``. + gcs_data_source (google.cloud.storage_transfer_v1.types.GcsData): + A Cloud Storage data source. + + This field is a member of `oneof`_ ``data_source``. + aws_s3_data_source (google.cloud.storage_transfer_v1.types.AwsS3Data): + An AWS S3 data source. + + This field is a member of `oneof`_ ``data_source``. + http_data_source (google.cloud.storage_transfer_v1.types.HttpData): + An HTTP URL data source. + + This field is a member of `oneof`_ ``data_source``. + posix_data_source (google.cloud.storage_transfer_v1.types.PosixFilesystem): + A POSIX Filesystem data source. + + This field is a member of `oneof`_ ``data_source``. + azure_blob_storage_data_source (google.cloud.storage_transfer_v1.types.AzureBlobStorageData): + An Azure Blob Storage data source. + + This field is a member of `oneof`_ ``data_source``. + aws_s3_compatible_data_source (google.cloud.storage_transfer_v1.types.AwsS3CompatibleData): + An AWS S3 compatible data source. + + This field is a member of `oneof`_ ``data_source``. + hdfs_data_source (google.cloud.storage_transfer_v1.types.HdfsData): + An HDFS cluster data source. + + This field is a member of `oneof`_ ``data_source``. + gcs_intermediate_data_location (google.cloud.storage_transfer_v1.types.GcsData): + For transfers between file systems, specifies a Cloud + Storage bucket to be used as an intermediate location + through which to transfer data. + + See `Transfer data between file + systems `__ + for more information. + + This field is a member of `oneof`_ ``intermediate_data_location``. + object_conditions (google.cloud.storage_transfer_v1.types.ObjectConditions): + Only objects that satisfy these object + conditions are included in the set of data + source and data sink objects. Object conditions + based on objects' "last modification time" do + not exclude objects in a data sink. + transfer_options (google.cloud.storage_transfer_v1.types.TransferOptions): + If the option + [delete_objects_unique_in_sink][google.storagetransfer.v1.TransferOptions.delete_objects_unique_in_sink] + is ``true`` and time-based object conditions such as 'last + modification time' are specified, the request fails with an + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] error. + transfer_manifest (google.cloud.storage_transfer_v1.types.TransferManifest): + A manifest file provides a list of objects to + be transferred from the data source. This field + points to the location of the manifest file. + Otherwise, the entire source bucket is used. + ObjectConditions still apply. + source_agent_pool_name (str): + Specifies the agent pool name associated with + the posix data source. When unspecified, the + default name is used. + sink_agent_pool_name (str): + Specifies the agent pool name associated with + the posix data sink. When unspecified, the + default name is used. + """ + + gcs_data_sink: 'GcsData' = proto.Field( + proto.MESSAGE, + number=4, + oneof='data_sink', + message='GcsData', + ) + posix_data_sink: 'PosixFilesystem' = proto.Field( + proto.MESSAGE, + number=13, + oneof='data_sink', + message='PosixFilesystem', + ) + gcs_data_source: 'GcsData' = proto.Field( + proto.MESSAGE, + number=1, + oneof='data_source', + message='GcsData', + ) + aws_s3_data_source: 'AwsS3Data' = proto.Field( + proto.MESSAGE, + number=2, + oneof='data_source', + message='AwsS3Data', + ) + http_data_source: 'HttpData' = proto.Field( + proto.MESSAGE, + number=3, + oneof='data_source', + message='HttpData', + ) + posix_data_source: 'PosixFilesystem' = proto.Field( + proto.MESSAGE, + number=14, + oneof='data_source', + message='PosixFilesystem', + ) + azure_blob_storage_data_source: 'AzureBlobStorageData' = proto.Field( + proto.MESSAGE, + number=8, + oneof='data_source', + message='AzureBlobStorageData', + ) + aws_s3_compatible_data_source: 'AwsS3CompatibleData' = proto.Field( + proto.MESSAGE, + number=19, + oneof='data_source', + message='AwsS3CompatibleData', + ) + hdfs_data_source: 'HdfsData' = proto.Field( + proto.MESSAGE, + number=20, + oneof='data_source', + message='HdfsData', + ) + gcs_intermediate_data_location: 'GcsData' = proto.Field( + proto.MESSAGE, + number=16, + oneof='intermediate_data_location', + message='GcsData', + ) + object_conditions: 'ObjectConditions' = proto.Field( + proto.MESSAGE, + number=5, + message='ObjectConditions', + ) + transfer_options: 'TransferOptions' = proto.Field( + proto.MESSAGE, + number=6, + message='TransferOptions', + ) + transfer_manifest: 'TransferManifest' = proto.Field( + proto.MESSAGE, + number=15, + message='TransferManifest', + ) + source_agent_pool_name: str = proto.Field( + proto.STRING, + number=17, + ) + sink_agent_pool_name: str = proto.Field( + proto.STRING, + number=18, + ) + + +class MetadataOptions(proto.Message): + r"""Specifies the metadata options for running a transfer. + + Attributes: + symlink (google.cloud.storage_transfer_v1.types.MetadataOptions.Symlink): + Specifies how symlinks should be handled by + the transfer. By default, symlinks are not + preserved. Only applicable to transfers + involving POSIX file systems, and ignored for + other transfers. + mode (google.cloud.storage_transfer_v1.types.MetadataOptions.Mode): + Specifies how each file's mode attribute + should be handled by the transfer. By default, + mode is not preserved. Only applicable to + transfers involving POSIX file systems, and + ignored for other transfers. + gid (google.cloud.storage_transfer_v1.types.MetadataOptions.GID): + Specifies how each file's POSIX group ID + (GID) attribute should be handled by the + transfer. By default, GID is not preserved. Only + applicable to transfers involving POSIX file + systems, and ignored for other transfers. + uid (google.cloud.storage_transfer_v1.types.MetadataOptions.UID): + Specifies how each file's POSIX user ID (UID) + attribute should be handled by the transfer. By + default, UID is not preserved. Only applicable + to transfers involving POSIX file systems, and + ignored for other transfers. + acl (google.cloud.storage_transfer_v1.types.MetadataOptions.Acl): + Specifies how each object's ACLs should be preserved for + transfers between Google Cloud Storage buckets. If + unspecified, the default behavior is the same as + ACL_DESTINATION_BUCKET_DEFAULT. + storage_class (google.cloud.storage_transfer_v1.types.MetadataOptions.StorageClass): + Specifies the storage class to set on objects being + transferred to Google Cloud Storage buckets. If unspecified, + the default behavior is the same as + [STORAGE_CLASS_DESTINATION_BUCKET_DEFAULT][google.storagetransfer.v1.MetadataOptions.StorageClass.STORAGE_CLASS_DESTINATION_BUCKET_DEFAULT]. + temporary_hold (google.cloud.storage_transfer_v1.types.MetadataOptions.TemporaryHold): + Specifies how each object's temporary hold status should be + preserved for transfers between Google Cloud Storage + buckets. If unspecified, the default behavior is the same as + [TEMPORARY_HOLD_PRESERVE][google.storagetransfer.v1.MetadataOptions.TemporaryHold.TEMPORARY_HOLD_PRESERVE]. + kms_key (google.cloud.storage_transfer_v1.types.MetadataOptions.KmsKey): + Specifies how each object's Cloud KMS customer-managed + encryption key (CMEK) is preserved for transfers between + Google Cloud Storage buckets. If unspecified, the default + behavior is the same as + [KMS_KEY_DESTINATION_BUCKET_DEFAULT][google.storagetransfer.v1.MetadataOptions.KmsKey.KMS_KEY_DESTINATION_BUCKET_DEFAULT]. + time_created (google.cloud.storage_transfer_v1.types.MetadataOptions.TimeCreated): + Specifies how each object's ``timeCreated`` metadata is + preserved for transfers. If unspecified, the default + behavior is the same as + [TIME_CREATED_SKIP][google.storagetransfer.v1.MetadataOptions.TimeCreated.TIME_CREATED_SKIP]. + This behavior is supported for transfers to Cloud Storage + buckets from Cloud Storage, Amazon S3, S3-compatible + storage, and Azure sources. + """ + class Symlink(proto.Enum): + r"""Whether symlinks should be skipped or preserved during a + transfer job. + + Values: + SYMLINK_UNSPECIFIED (0): + Symlink behavior is unspecified. + SYMLINK_SKIP (1): + Do not preserve symlinks during a transfer + job. + SYMLINK_PRESERVE (2): + Preserve symlinks during a transfer job. + """ + SYMLINK_UNSPECIFIED = 0 + SYMLINK_SKIP = 1 + SYMLINK_PRESERVE = 2 + + class Mode(proto.Enum): + r"""Options for handling file mode attribute. + + Values: + MODE_UNSPECIFIED (0): + Mode behavior is unspecified. + MODE_SKIP (1): + Do not preserve mode during a transfer job. + MODE_PRESERVE (2): + Preserve mode during a transfer job. + """ + MODE_UNSPECIFIED = 0 + MODE_SKIP = 1 + MODE_PRESERVE = 2 + + class GID(proto.Enum): + r"""Options for handling file GID attribute. + + Values: + GID_UNSPECIFIED (0): + GID behavior is unspecified. + GID_SKIP (1): + Do not preserve GID during a transfer job. + GID_NUMBER (2): + Preserve GID during a transfer job. + """ + GID_UNSPECIFIED = 0 + GID_SKIP = 1 + GID_NUMBER = 2 + + class UID(proto.Enum): + r"""Options for handling file UID attribute. + + Values: + UID_UNSPECIFIED (0): + UID behavior is unspecified. + UID_SKIP (1): + Do not preserve UID during a transfer job. + UID_NUMBER (2): + Preserve UID during a transfer job. + """ + UID_UNSPECIFIED = 0 + UID_SKIP = 1 + UID_NUMBER = 2 + + class Acl(proto.Enum): + r"""Options for handling Cloud Storage object ACLs. + + Values: + ACL_UNSPECIFIED (0): + ACL behavior is unspecified. + ACL_DESTINATION_BUCKET_DEFAULT (1): + Use the destination bucket's default object + ACLS, if applicable. + ACL_PRESERVE (2): + Preserve the object's original ACLs. This requires the + service account to have ``storage.objects.getIamPolicy`` + permission for the source object. `Uniform bucket-level + access `__ + must not be enabled on either the source or destination + buckets. + """ + ACL_UNSPECIFIED = 0 + ACL_DESTINATION_BUCKET_DEFAULT = 1 + ACL_PRESERVE = 2 + + class StorageClass(proto.Enum): + r"""Options for handling Google Cloud Storage object storage + class. + + Values: + STORAGE_CLASS_UNSPECIFIED (0): + Storage class behavior is unspecified. + STORAGE_CLASS_DESTINATION_BUCKET_DEFAULT (1): + Use the destination bucket's default storage + class. + STORAGE_CLASS_PRESERVE (2): + Preserve the object's original storage class. This is only + supported for transfers from Google Cloud Storage buckets. + REGIONAL and MULTI_REGIONAL storage classes will be mapped + to STANDARD to ensure they can be written to the destination + bucket. + STORAGE_CLASS_STANDARD (3): + Set the storage class to STANDARD. + STORAGE_CLASS_NEARLINE (4): + Set the storage class to NEARLINE. + STORAGE_CLASS_COLDLINE (5): + Set the storage class to COLDLINE. + STORAGE_CLASS_ARCHIVE (6): + Set the storage class to ARCHIVE. + """ + STORAGE_CLASS_UNSPECIFIED = 0 + STORAGE_CLASS_DESTINATION_BUCKET_DEFAULT = 1 + STORAGE_CLASS_PRESERVE = 2 + STORAGE_CLASS_STANDARD = 3 + STORAGE_CLASS_NEARLINE = 4 + STORAGE_CLASS_COLDLINE = 5 + STORAGE_CLASS_ARCHIVE = 6 + + class TemporaryHold(proto.Enum): + r"""Options for handling temporary holds for Google Cloud Storage + objects. + + Values: + TEMPORARY_HOLD_UNSPECIFIED (0): + Temporary hold behavior is unspecified. + TEMPORARY_HOLD_SKIP (1): + Do not set a temporary hold on the + destination object. + TEMPORARY_HOLD_PRESERVE (2): + Preserve the object's original temporary hold + status. + """ + TEMPORARY_HOLD_UNSPECIFIED = 0 + TEMPORARY_HOLD_SKIP = 1 + TEMPORARY_HOLD_PRESERVE = 2 + + class KmsKey(proto.Enum): + r"""Options for handling the KmsKey setting for Google Cloud + Storage objects. + + Values: + KMS_KEY_UNSPECIFIED (0): + KmsKey behavior is unspecified. + KMS_KEY_DESTINATION_BUCKET_DEFAULT (1): + Use the destination bucket's default + encryption settings. + KMS_KEY_PRESERVE (2): + Preserve the object's original Cloud KMS + customer-managed encryption key (CMEK) if + present. Objects that do not use a Cloud KMS + encryption key will be encrypted using the + destination bucket's encryption settings. + """ + KMS_KEY_UNSPECIFIED = 0 + KMS_KEY_DESTINATION_BUCKET_DEFAULT = 1 + KMS_KEY_PRESERVE = 2 + + class TimeCreated(proto.Enum): + r"""Options for handling ``timeCreated`` metadata for Google Cloud + Storage objects. + + Values: + TIME_CREATED_UNSPECIFIED (0): + TimeCreated behavior is unspecified. + TIME_CREATED_SKIP (1): + Do not preserve the ``timeCreated`` metadata from the source + object. + TIME_CREATED_PRESERVE_AS_CUSTOM_TIME (2): + Preserves the source object's ``timeCreated`` or + ``lastModified`` metadata in the ``customTime`` field in the + destination object. Note that any value stored in the source + object's ``customTime`` field will not be propagated to the + destination object. + """ + TIME_CREATED_UNSPECIFIED = 0 + TIME_CREATED_SKIP = 1 + TIME_CREATED_PRESERVE_AS_CUSTOM_TIME = 2 + + symlink: Symlink = proto.Field( + proto.ENUM, + number=1, + enum=Symlink, + ) + mode: Mode = proto.Field( + proto.ENUM, + number=2, + enum=Mode, + ) + gid: GID = proto.Field( + proto.ENUM, + number=3, + enum=GID, + ) + uid: UID = proto.Field( + proto.ENUM, + number=4, + enum=UID, + ) + acl: Acl = proto.Field( + proto.ENUM, + number=5, + enum=Acl, + ) + storage_class: StorageClass = proto.Field( + proto.ENUM, + number=6, + enum=StorageClass, + ) + temporary_hold: TemporaryHold = proto.Field( + proto.ENUM, + number=7, + enum=TemporaryHold, + ) + kms_key: KmsKey = proto.Field( + proto.ENUM, + number=8, + enum=KmsKey, + ) + time_created: TimeCreated = proto.Field( + proto.ENUM, + number=9, + enum=TimeCreated, + ) + + +class TransferManifest(proto.Message): + r"""Specifies where the manifest is located. + + Attributes: + location (str): + Specifies the path to the manifest in Cloud Storage. The + Google-managed service account for the transfer must have + ``storage.objects.get`` permission for this object. An + example path is ``gs://bucket_name/path/manifest.csv``. + """ + + location: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Schedule(proto.Message): + r"""Transfers can be scheduled to recur or to run just once. + + Attributes: + schedule_start_date (google.type.date_pb2.Date): + Required. The start date of a transfer. Date boundaries are + determined relative to UTC time. If ``schedule_start_date`` + and + [start_time_of_day][google.storagetransfer.v1.Schedule.start_time_of_day] + are in the past relative to the job's creation time, the + transfer starts the day after you schedule the transfer + request. + + **Note:** When starting jobs at or near midnight UTC it is + possible that a job starts later than expected. For example, + if you send an outbound request on June 1 one millisecond + prior to midnight UTC and the Storage Transfer Service + server receives the request on June 2, then it creates a + TransferJob with ``schedule_start_date`` set to June 2 and a + ``start_time_of_day`` set to midnight UTC. The first + scheduled + [TransferOperation][google.storagetransfer.v1.TransferOperation] + takes place on June 3 at midnight UTC. + schedule_end_date (google.type.date_pb2.Date): + The last day a transfer runs. Date boundaries are determined + relative to UTC time. A job runs once per 24 hours within + the following guidelines: + + - If ``schedule_end_date`` and + [schedule_start_date][google.storagetransfer.v1.Schedule.schedule_start_date] + are the same and in the future relative to UTC, the + transfer is executed only one time. + - If ``schedule_end_date`` is later than + ``schedule_start_date`` and ``schedule_end_date`` is in + the future relative to UTC, the job runs each day at + [start_time_of_day][google.storagetransfer.v1.Schedule.start_time_of_day] + through ``schedule_end_date``. + start_time_of_day (google.type.timeofday_pb2.TimeOfDay): + The time in UTC that a transfer job is scheduled to run. + Transfers may start later than this time. + + If ``start_time_of_day`` is not specified: + + - One-time transfers run immediately. + - Recurring transfers run immediately, and each day at + midnight UTC, through + [schedule_end_date][google.storagetransfer.v1.Schedule.schedule_end_date]. + + If ``start_time_of_day`` is specified: + + - One-time transfers run at the specified time. + - Recurring transfers run at the specified time each day, + through ``schedule_end_date``. + end_time_of_day (google.type.timeofday_pb2.TimeOfDay): + The time in UTC that no further transfer operations are + scheduled. Combined with + [schedule_end_date][google.storagetransfer.v1.Schedule.schedule_end_date], + ``end_time_of_day`` specifies the end date and time for + starting new transfer operations. This field must be greater + than or equal to the timestamp corresponding to the + combintation of + [schedule_start_date][google.storagetransfer.v1.Schedule.schedule_start_date] + and + [start_time_of_day][google.storagetransfer.v1.Schedule.start_time_of_day], + and is subject to the following: + + - If ``end_time_of_day`` is not set and + ``schedule_end_date`` is set, then a default value of + ``23:59:59`` is used for ``end_time_of_day``. + + - If ``end_time_of_day`` is set and ``schedule_end_date`` + is not set, then + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] is + returned. + repeat_interval (google.protobuf.duration_pb2.Duration): + Interval between the start of each scheduled + TransferOperation. If unspecified, the default + value is 24 hours. This value may not be less + than 1 hour. + """ + + schedule_start_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + schedule_end_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + start_time_of_day: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=3, + message=timeofday_pb2.TimeOfDay, + ) + end_time_of_day: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=4, + message=timeofday_pb2.TimeOfDay, + ) + repeat_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + +class EventStream(proto.Message): + r"""Specifies the Event-driven transfer options. Event-driven + transfers listen to an event stream to transfer updated files. + + Attributes: + name (str): + Required. Specifies a unique name of the resource such as + AWS SQS ARN in the form + 'arn:aws:sqs:region:account_id:queue_name', or Pub/Sub + subscription resource name in the form + 'projects/{project}/subscriptions/{sub}'. + event_stream_start_time (google.protobuf.timestamp_pb2.Timestamp): + Specifies the date and time that Storage + Transfer Service starts listening for events + from this stream. If no start time is specified + or start time is in the past, Storage Transfer + Service starts listening immediately. + event_stream_expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Specifies the data and time at which Storage + Transfer Service stops listening for events from + this stream. After this time, any transfers in + progress will complete, but no new transfers are + initiated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_stream_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + event_stream_expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class TransferJob(proto.Message): + r"""This resource represents the configuration of a transfer job + that runs periodically. + + Attributes: + name (str): + A unique name (within the transfer project) assigned when + the job is created. If this field is empty in a + CreateTransferJobRequest, Storage Transfer Service assigns a + unique name. Otherwise, the specified name is used as the + unique name for this job. + + If the specified name is in use by a job, the creation + request fails with an + [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error. + + This name must start with ``"transferJobs/"`` prefix and end + with a letter or a number, and should be no more than 128 + characters. For transfers involving PosixFilesystem, this + name must start with ``transferJobs/OPI`` specifically. For + all other transfer types, this name must not start with + ``transferJobs/OPI``. + + Non-PosixFilesystem example: + ``"transferJobs/^(?!OPI)[A-Za-z0-9-._~]*[A-Za-z0-9]$"`` + + PosixFilesystem example: + ``"transferJobs/OPI^[A-Za-z0-9-._~]*[A-Za-z0-9]$"`` + + Applications must not rely on the enforcement of naming + requirements involving OPI. + + Invalid job names fail with an + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] error. + description (str): + A description provided by the user for the + job. Its max length is 1024 bytes when + Unicode-encoded. + project_id (str): + The ID of the Google Cloud project that owns + the job. + transfer_spec (google.cloud.storage_transfer_v1.types.TransferSpec): + Transfer specification. + notification_config (google.cloud.storage_transfer_v1.types.NotificationConfig): + Notification configuration. + logging_config (google.cloud.storage_transfer_v1.types.LoggingConfig): + Logging configuration. + schedule (google.cloud.storage_transfer_v1.types.Schedule): + Specifies schedule for the transfer job. + This is an optional field. When the field is not + set, the job never executes a transfer, unless + you invoke RunTransferJob or update the job to + have a non-empty schedule. + event_stream (google.cloud.storage_transfer_v1.types.EventStream): + Specifies the event stream for the transfer + job for event-driven transfers. When EventStream + is specified, the Schedule fields are ignored. + status (google.cloud.storage_transfer_v1.types.TransferJob.Status): + Status of the job. This value MUST be specified for + ``CreateTransferJobRequests``. + + **Note:** The effect of the new job status takes place + during a subsequent job run. For example, if you change the + job status from + [ENABLED][google.storagetransfer.v1.TransferJob.Status.ENABLED] + to + [DISABLED][google.storagetransfer.v1.TransferJob.Status.DISABLED], + and an operation spawned by the transfer is running, the + status change would not affect the current operation. + creation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time that the transfer job + was created. + last_modification_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time that the transfer job + was last modified. + deletion_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time that the transfer job + was deleted. + latest_operation_name (str): + The name of the most recently started + TransferOperation of this JobConfig. Present if + a TransferOperation has been created for this + JobConfig. + """ + class Status(proto.Enum): + r"""The status of the transfer job. + + Values: + STATUS_UNSPECIFIED (0): + Zero is an illegal value. + ENABLED (1): + New transfers are performed based on the + schedule. + DISABLED (2): + New transfers are not scheduled. + DELETED (3): + This is a soft delete state. After a transfer job is set to + this state, the job and all the transfer executions are + subject to garbage collection. Transfer jobs become eligible + for garbage collection 30 days after their status is set to + ``DELETED``. + """ + STATUS_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + DELETED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + project_id: str = proto.Field( + proto.STRING, + number=3, + ) + transfer_spec: 'TransferSpec' = proto.Field( + proto.MESSAGE, + number=4, + message='TransferSpec', + ) + notification_config: 'NotificationConfig' = proto.Field( + proto.MESSAGE, + number=11, + message='NotificationConfig', + ) + logging_config: 'LoggingConfig' = proto.Field( + proto.MESSAGE, + number=14, + message='LoggingConfig', + ) + schedule: 'Schedule' = proto.Field( + proto.MESSAGE, + number=5, + message='Schedule', + ) + event_stream: 'EventStream' = proto.Field( + proto.MESSAGE, + number=15, + message='EventStream', + ) + status: Status = proto.Field( + proto.ENUM, + number=6, + enum=Status, + ) + creation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + last_modification_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + deletion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + latest_operation_name: str = proto.Field( + proto.STRING, + number=12, + ) + + +class ErrorLogEntry(proto.Message): + r"""An entry describing an error that has occurred. + + Attributes: + url (str): + Required. A URL that refers to the target (a + data source, a data sink, or an object) with + which the error is associated. + error_details (MutableSequence[str]): + A list of messages that carry the error + details. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + error_details: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ErrorSummary(proto.Message): + r"""A summary of errors by error code, plus a count and sample + error log entries. + + Attributes: + error_code (google.rpc.code_pb2.Code): + Required. + error_count (int): + Required. Count of this type of error. + error_log_entries (MutableSequence[google.cloud.storage_transfer_v1.types.ErrorLogEntry]): + Error samples. + + At most 5 error log entries are recorded for a + given error code for a single transfer + operation. + """ + + error_code: code_pb2.Code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + error_count: int = proto.Field( + proto.INT64, + number=2, + ) + error_log_entries: MutableSequence['ErrorLogEntry'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ErrorLogEntry', + ) + + +class TransferCounters(proto.Message): + r"""A collection of counters that report the progress of a + transfer operation. + + Attributes: + objects_found_from_source (int): + Objects found in the data source that are + scheduled to be transferred, excluding any that + are filtered based on object conditions or + skipped due to sync. + bytes_found_from_source (int): + Bytes found in the data source that are + scheduled to be transferred, excluding any that + are filtered based on object conditions or + skipped due to sync. + objects_found_only_from_sink (int): + Objects found only in the data sink that are + scheduled to be deleted. + bytes_found_only_from_sink (int): + Bytes found only in the data sink that are + scheduled to be deleted. + objects_from_source_skipped_by_sync (int): + Objects in the data source that are not + transferred because they already exist in the + data sink. + bytes_from_source_skipped_by_sync (int): + Bytes in the data source that are not + transferred because they already exist in the + data sink. + objects_copied_to_sink (int): + Objects that are copied to the data sink. + bytes_copied_to_sink (int): + Bytes that are copied to the data sink. + objects_deleted_from_source (int): + Objects that are deleted from the data + source. + bytes_deleted_from_source (int): + Bytes that are deleted from the data source. + objects_deleted_from_sink (int): + Objects that are deleted from the data sink. + bytes_deleted_from_sink (int): + Bytes that are deleted from the data sink. + objects_from_source_failed (int): + Objects in the data source that failed to be + transferred or that failed to be deleted after + being transferred. + bytes_from_source_failed (int): + Bytes in the data source that failed to be + transferred or that failed to be deleted after + being transferred. + objects_failed_to_delete_from_sink (int): + Objects that failed to be deleted from the + data sink. + bytes_failed_to_delete_from_sink (int): + Bytes that failed to be deleted from the data + sink. + directories_found_from_source (int): + For transfers involving PosixFilesystem only. + + Number of directories found while listing. For example, if + the root directory of the transfer is ``base/`` and there + are two other directories, ``a/`` and ``b/`` under this + directory, the count after listing ``base/``, ``base/a/`` + and ``base/b/`` is 3. + directories_failed_to_list_from_source (int): + For transfers involving PosixFilesystem only. + + Number of listing failures for each directory + found at the source. Potential failures when + listing a directory include permission failure + or block failure. If listing a directory fails, + no files in the directory are transferred. + directories_successfully_listed_from_source (int): + For transfers involving PosixFilesystem only. + + Number of successful listings for each directory + found at the source. + intermediate_objects_cleaned_up (int): + Number of successfully cleaned up + intermediate objects. + intermediate_objects_failed_cleaned_up (int): + Number of intermediate objects failed cleaned + up. + """ + + objects_found_from_source: int = proto.Field( + proto.INT64, + number=1, + ) + bytes_found_from_source: int = proto.Field( + proto.INT64, + number=2, + ) + objects_found_only_from_sink: int = proto.Field( + proto.INT64, + number=3, + ) + bytes_found_only_from_sink: int = proto.Field( + proto.INT64, + number=4, + ) + objects_from_source_skipped_by_sync: int = proto.Field( + proto.INT64, + number=5, + ) + bytes_from_source_skipped_by_sync: int = proto.Field( + proto.INT64, + number=6, + ) + objects_copied_to_sink: int = proto.Field( + proto.INT64, + number=7, + ) + bytes_copied_to_sink: int = proto.Field( + proto.INT64, + number=8, + ) + objects_deleted_from_source: int = proto.Field( + proto.INT64, + number=9, + ) + bytes_deleted_from_source: int = proto.Field( + proto.INT64, + number=10, + ) + objects_deleted_from_sink: int = proto.Field( + proto.INT64, + number=11, + ) + bytes_deleted_from_sink: int = proto.Field( + proto.INT64, + number=12, + ) + objects_from_source_failed: int = proto.Field( + proto.INT64, + number=13, + ) + bytes_from_source_failed: int = proto.Field( + proto.INT64, + number=14, + ) + objects_failed_to_delete_from_sink: int = proto.Field( + proto.INT64, + number=15, + ) + bytes_failed_to_delete_from_sink: int = proto.Field( + proto.INT64, + number=16, + ) + directories_found_from_source: int = proto.Field( + proto.INT64, + number=17, + ) + directories_failed_to_list_from_source: int = proto.Field( + proto.INT64, + number=18, + ) + directories_successfully_listed_from_source: int = proto.Field( + proto.INT64, + number=19, + ) + intermediate_objects_cleaned_up: int = proto.Field( + proto.INT64, + number=22, + ) + intermediate_objects_failed_cleaned_up: int = proto.Field( + proto.INT64, + number=23, + ) + + +class NotificationConfig(proto.Message): + r"""Specification to configure notifications published to Pub/Sub. + Notifications are published to the customer-provided topic using the + following ``PubsubMessage.attributes``: + + - ``"eventType"``: one of the + [EventType][google.storagetransfer.v1.NotificationConfig.EventType] + values + - ``"payloadFormat"``: one of the + [PayloadFormat][google.storagetransfer.v1.NotificationConfig.PayloadFormat] + values + - ``"projectId"``: the + [project_id][google.storagetransfer.v1.TransferOperation.project_id] + of the ``TransferOperation`` + - ``"transferJobName"``: the + [transfer_job_name][google.storagetransfer.v1.TransferOperation.transfer_job_name] + of the ``TransferOperation`` + - ``"transferOperationName"``: the + [name][google.storagetransfer.v1.TransferOperation.name] of the + ``TransferOperation`` + + The ``PubsubMessage.data`` contains a + [TransferOperation][google.storagetransfer.v1.TransferOperation] + resource formatted according to the specified ``PayloadFormat``. + + Attributes: + pubsub_topic (str): + Required. The ``Topic.name`` of the Pub/Sub topic to which + to publish notifications. Must be of the format: + ``projects/{project}/topics/{topic}``. Not matching this + format results in an + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] error. + event_types (MutableSequence[google.cloud.storage_transfer_v1.types.NotificationConfig.EventType]): + Event types for which a notification is + desired. If empty, send notifications for all + event types. + payload_format (google.cloud.storage_transfer_v1.types.NotificationConfig.PayloadFormat): + Required. The desired format of the + notification message payloads. + """ + class EventType(proto.Enum): + r"""Enum for specifying event types for which notifications are + to be published. + + Additional event types may be added in the future. Clients + should either safely ignore unrecognized event types or + explicitly specify which event types they are prepared to + accept. + + Values: + EVENT_TYPE_UNSPECIFIED (0): + Illegal value, to avoid allowing a default. + TRANSFER_OPERATION_SUCCESS (1): + ``TransferOperation`` completed with status + [SUCCESS][google.storagetransfer.v1.TransferOperation.Status.SUCCESS]. + TRANSFER_OPERATION_FAILED (2): + ``TransferOperation`` completed with status + [FAILED][google.storagetransfer.v1.TransferOperation.Status.FAILED]. + TRANSFER_OPERATION_ABORTED (3): + ``TransferOperation`` completed with status + [ABORTED][google.storagetransfer.v1.TransferOperation.Status.ABORTED]. + """ + EVENT_TYPE_UNSPECIFIED = 0 + TRANSFER_OPERATION_SUCCESS = 1 + TRANSFER_OPERATION_FAILED = 2 + TRANSFER_OPERATION_ABORTED = 3 + + class PayloadFormat(proto.Enum): + r"""Enum for specifying the format of a notification message's + payload. + + Values: + PAYLOAD_FORMAT_UNSPECIFIED (0): + Illegal value, to avoid allowing a default. + NONE (1): + No payload is included with the notification. + JSON (2): + ``TransferOperation`` is `formatted as a JSON + response `__, + in application/json. + """ + PAYLOAD_FORMAT_UNSPECIFIED = 0 + NONE = 1 + JSON = 2 + + pubsub_topic: str = proto.Field( + proto.STRING, + number=1, + ) + event_types: MutableSequence[EventType] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=EventType, + ) + payload_format: PayloadFormat = proto.Field( + proto.ENUM, + number=3, + enum=PayloadFormat, + ) + + +class LoggingConfig(proto.Message): + r"""Specifies the logging behavior for transfer operations. + + Logs can be sent to Cloud Logging for all transfer types. See `Read + transfer + logs `__ + for details. + + Attributes: + log_actions (MutableSequence[google.cloud.storage_transfer_v1.types.LoggingConfig.LoggableAction]): + Specifies the actions to be logged. If empty, + no logs are generated. + log_action_states (MutableSequence[google.cloud.storage_transfer_v1.types.LoggingConfig.LoggableActionState]): + States in which ``log_actions`` are logged. If empty, no + logs are generated. + enable_onprem_gcs_transfer_logs (bool): + For PosixFilesystem transfers, enables `file system transfer + logs `__ + instead of, or in addition to, Cloud Logging. + + This option ignores [LoggableAction] and + [LoggableActionState]. If these are set, Cloud Logging will + also be enabled for this transfer. + """ + class LoggableAction(proto.Enum): + r"""Loggable actions. + + Values: + LOGGABLE_ACTION_UNSPECIFIED (0): + Default value. This value is unused. + FIND (1): + Listing objects in a bucket. + DELETE (2): + Deleting objects at the source or the + destination. + COPY (3): + Copying objects to Google Cloud Storage. + """ + LOGGABLE_ACTION_UNSPECIFIED = 0 + FIND = 1 + DELETE = 2 + COPY = 3 + + class LoggableActionState(proto.Enum): + r"""Loggable action states. + + Values: + LOGGABLE_ACTION_STATE_UNSPECIFIED (0): + Default value. This value is unused. + SUCCEEDED (1): + ``LoggableAction`` completed successfully. ``SUCCEEDED`` + actions are logged as + [INFO][google.logging.type.LogSeverity.INFO]. + FAILED (2): + ``LoggableAction`` terminated in an error state. ``FAILED`` + actions are logged as + [ERROR][google.logging.type.LogSeverity.ERROR]. + """ + LOGGABLE_ACTION_STATE_UNSPECIFIED = 0 + SUCCEEDED = 1 + FAILED = 2 + + log_actions: MutableSequence[LoggableAction] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=LoggableAction, + ) + log_action_states: MutableSequence[LoggableActionState] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=LoggableActionState, + ) + enable_onprem_gcs_transfer_logs: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class TransferOperation(proto.Message): + r"""A description of the execution of a transfer. + + Attributes: + name (str): + A globally unique ID assigned by the system. + project_id (str): + The ID of the Google Cloud project that owns + the operation. + transfer_spec (google.cloud.storage_transfer_v1.types.TransferSpec): + Transfer specification. + notification_config (google.cloud.storage_transfer_v1.types.NotificationConfig): + Notification configuration. + logging_config (google.cloud.storage_transfer_v1.types.LoggingConfig): + Cloud Logging configuration. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this transfer execution. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this transfer execution. + status (google.cloud.storage_transfer_v1.types.TransferOperation.Status): + Status of the transfer operation. + counters (google.cloud.storage_transfer_v1.types.TransferCounters): + Information about the progress of the + transfer operation. + error_breakdowns (MutableSequence[google.cloud.storage_transfer_v1.types.ErrorSummary]): + Summarizes errors encountered with sample + error log entries. + transfer_job_name (str): + The name of the transfer job that triggers + this transfer operation. + """ + class Status(proto.Enum): + r"""The status of a TransferOperation. + + Values: + STATUS_UNSPECIFIED (0): + Zero is an illegal value. + IN_PROGRESS (1): + In progress. + PAUSED (2): + Paused. + SUCCESS (3): + Completed successfully. + FAILED (4): + Terminated due to an unrecoverable failure. + ABORTED (5): + Aborted by the user. + QUEUED (6): + Temporarily delayed by the system. No user + action is required. + SUSPENDING (7): + The operation is suspending and draining the + ongoing work to completion. + """ + STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + PAUSED = 2 + SUCCESS = 3 + FAILED = 4 + ABORTED = 5 + QUEUED = 6 + SUSPENDING = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + transfer_spec: 'TransferSpec' = proto.Field( + proto.MESSAGE, + number=3, + message='TransferSpec', + ) + notification_config: 'NotificationConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='NotificationConfig', + ) + logging_config: 'LoggingConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='LoggingConfig', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + status: Status = proto.Field( + proto.ENUM, + number=6, + enum=Status, + ) + counters: 'TransferCounters' = proto.Field( + proto.MESSAGE, + number=7, + message='TransferCounters', + ) + error_breakdowns: MutableSequence['ErrorSummary'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='ErrorSummary', + ) + transfer_job_name: str = proto.Field( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/mypy.ini b/owl-bot-staging/google-cloud-storage-transfer/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/noxfile.py b/owl-bot-staging/google-cloud-storage-transfer/v1/noxfile.py new file mode 100644 index 000000000000..4f5cad33d8e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/noxfile.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-storage-transfer' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/storage_transfer_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/storage_transfer_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json new file mode 100644 index 000000000000..f3c5ac4b04c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json @@ -0,0 +1,2197 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.storagetransfer.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-storage-transfer", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.create_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.CreateAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "CreateAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.CreateAgentPoolRequest" + }, + { + "name": "project_id", + "type": "str" + }, + { + "name": "agent_pool", + "type": "google.cloud.storage_transfer_v1.types.AgentPool" + }, + { + "name": "agent_pool_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.storage_transfer_v1.types.AgentPool", + "shortName": "create_agent_pool" + }, + "description": "Sample for CreateAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.create_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.CreateAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "CreateAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.CreateAgentPoolRequest" + }, + { + "name": "project_id", + "type": "str" + }, + { + "name": "agent_pool", + "type": "google.cloud.storage_transfer_v1.types.AgentPool" + }, + { + "name": "agent_pool_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.storage_transfer_v1.types.AgentPool", + "shortName": "create_agent_pool" + }, + "description": "Sample for CreateAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.create_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.CreateTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "CreateTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.CreateTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "create_transfer_job" + }, + "description": "Sample for CreateTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.create_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.CreateTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "CreateTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.CreateTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "create_transfer_job" + }, + "description": "Sample for CreateTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.delete_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.DeleteAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "DeleteAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.DeleteAgentPoolRequest" + }, + { + "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_agent_pool" + }, + "description": "Sample for DeleteAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_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": "storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.delete_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.DeleteAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "DeleteAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.DeleteAgentPoolRequest" + }, + { + "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_agent_pool" + }, + "description": "Sample for DeleteAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_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": "storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.delete_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.DeleteTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "DeleteTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.DeleteTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_transfer_job" + }, + "description": "Sample for DeleteTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.delete_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.DeleteTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "DeleteTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.DeleteTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_transfer_job" + }, + "description": "Sample for DeleteTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.get_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetAgentPoolRequest" + }, + { + "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.storage_transfer_v1.types.AgentPool", + "shortName": "get_agent_pool" + }, + "description": "Sample for GetAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetAgentPool_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": "storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.get_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetAgentPoolRequest" + }, + { + "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.storage_transfer_v1.types.AgentPool", + "shortName": "get_agent_pool" + }, + "description": "Sample for GetAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetAgentPool_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": "storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.get_google_service_account", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetGoogleServiceAccount", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetGoogleServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetGoogleServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.GoogleServiceAccount", + "shortName": "get_google_service_account" + }, + "description": "Sample for GetGoogleServiceAccount", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_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": "storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.get_google_service_account", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetGoogleServiceAccount", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetGoogleServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetGoogleServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.GoogleServiceAccount", + "shortName": "get_google_service_account" + }, + "description": "Sample for GetGoogleServiceAccount", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_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": "storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.get_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "get_transfer_job" + }, + "description": "Sample for GetTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.get_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.GetTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "GetTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.GetTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "get_transfer_job" + }, + "description": "Sample for GetTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_GetTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.list_agent_pools", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ListAgentPools", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ListAgentPools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest" + }, + { + "name": "project_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.storage_transfer_v1.services.storage_transfer_service.pagers.ListAgentPoolsAsyncPager", + "shortName": "list_agent_pools" + }, + "description": "Sample for ListAgentPools", + "file": "storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ListAgentPools_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": "storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.list_agent_pools", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ListAgentPools", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ListAgentPools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ListAgentPoolsRequest" + }, + { + "name": "project_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.storage_transfer_v1.services.storage_transfer_service.pagers.ListAgentPoolsPager", + "shortName": "list_agent_pools" + }, + "description": "Sample for ListAgentPools", + "file": "storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ListAgentPools_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": "storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.list_transfer_jobs", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ListTransferJobs", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ListTransferJobs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ListTransferJobsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.services.storage_transfer_service.pagers.ListTransferJobsAsyncPager", + "shortName": "list_transfer_jobs" + }, + "description": "Sample for ListTransferJobs", + "file": "storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_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": "storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.list_transfer_jobs", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ListTransferJobs", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ListTransferJobs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ListTransferJobsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.services.storage_transfer_service.pagers.ListTransferJobsPager", + "shortName": "list_transfer_jobs" + }, + "description": "Sample for ListTransferJobs", + "file": "storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_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": "storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.pause_transfer_operation", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.PauseTransferOperation", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "PauseTransferOperation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.PauseTransferOperationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "pause_transfer_operation" + }, + "description": "Sample for PauseTransferOperation", + "file": "storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_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": "storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.pause_transfer_operation", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.PauseTransferOperation", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "PauseTransferOperation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.PauseTransferOperationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "pause_transfer_operation" + }, + "description": "Sample for PauseTransferOperation", + "file": "storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_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": "storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.resume_transfer_operation", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ResumeTransferOperation", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ResumeTransferOperation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ResumeTransferOperationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "resume_transfer_operation" + }, + "description": "Sample for ResumeTransferOperation", + "file": "storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_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": "storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.resume_transfer_operation", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.ResumeTransferOperation", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "ResumeTransferOperation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.ResumeTransferOperationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "resume_transfer_operation" + }, + "description": "Sample for ResumeTransferOperation", + "file": "storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_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": "storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.run_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.RunTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "RunTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.RunTransferJobRequest" + }, + { + "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": "run_transfer_job" + }, + "description": "Sample for RunTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_RunTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.run_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.RunTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "RunTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.RunTransferJobRequest" + }, + { + "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": "run_transfer_job" + }, + "description": "Sample for RunTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_RunTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.update_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.UpdateAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "UpdateAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.UpdateAgentPoolRequest" + }, + { + "name": "agent_pool", + "type": "google.cloud.storage_transfer_v1.types.AgentPool" + }, + { + "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.storage_transfer_v1.types.AgentPool", + "shortName": "update_agent_pool" + }, + "description": "Sample for UpdateAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.update_agent_pool", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.UpdateAgentPool", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "UpdateAgentPool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.UpdateAgentPoolRequest" + }, + { + "name": "agent_pool", + "type": "google.cloud.storage_transfer_v1.types.AgentPool" + }, + { + "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.storage_transfer_v1.types.AgentPool", + "shortName": "update_agent_pool" + }, + "description": "Sample for UpdateAgentPool", + "file": "storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient", + "shortName": "StorageTransferServiceAsyncClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceAsyncClient.update_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.UpdateTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "UpdateTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.UpdateTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "update_transfer_job" + }, + "description": "Sample for UpdateTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient", + "shortName": "StorageTransferServiceClient" + }, + "fullName": "google.cloud.storage_transfer_v1.StorageTransferServiceClient.update_transfer_job", + "method": { + "fullName": "google.storagetransfer.v1.StorageTransferService.UpdateTransferJob", + "service": { + "fullName": "google.storagetransfer.v1.StorageTransferService", + "shortName": "StorageTransferService" + }, + "shortName": "UpdateTransferJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_transfer_v1.types.UpdateTransferJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.storage_transfer_v1.types.TransferJob", + "shortName": "update_transfer_job" + }, + "description": "Sample for UpdateTransferJob", + "file": "storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_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": "storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_async.py new file mode 100644 index 000000000000..cac7523ed90b --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_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 storage_transfer_v1 + + +async def sample_create_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.CreateAgentPoolRequest( + project_id="project_id_value", + agent_pool=agent_pool, + agent_pool_id="agent_pool_id_value", + ) + + # Make the request + response = await client.create_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_sync.py new file mode 100644 index 000000000000..e1607611dea2 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_agent_pool_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_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 storage_transfer_v1 + + +def sample_create_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.CreateAgentPoolRequest( + project_id="project_id_value", + agent_pool=agent_pool, + agent_pool_id="agent_pool_id_value", + ) + + # Make the request + response = client.create_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_CreateAgentPool_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_async.py new file mode 100644 index 000000000000..79525236c18f --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_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 storage_transfer_v1 + + +async def sample_create_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.CreateTransferJobRequest( + ) + + # Make the request + response = await client.create_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_sync.py new file mode 100644 index 000000000000..63a1ce1300ea --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_create_transfer_job_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_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 storage_transfer_v1 + + +def sample_create_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.CreateTransferJobRequest( + ) + + # Make the request + response = client.create_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_CreateTransferJob_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_async.py new file mode 100644 index 000000000000..c85f32d9019a --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_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 storage_transfer_v1 + + +async def sample_delete_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteAgentPoolRequest( + name="name_value", + ) + + # Make the request + await client.delete_agent_pool(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_sync.py new file mode 100644 index 000000000000..efd42d07bd48 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_agent_pool_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_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 storage_transfer_v1 + + +def sample_delete_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteAgentPoolRequest( + name="name_value", + ) + + # Make the request + client.delete_agent_pool(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_DeleteAgentPool_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_async.py new file mode 100644 index 000000000000..f39a559dfb44 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_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 storage_transfer_v1 + + +async def sample_delete_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + await client.delete_transfer_job(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_sync.py new file mode 100644 index 000000000000..1281acb18ad4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_delete_transfer_job_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_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 storage_transfer_v1 + + +def sample_delete_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.DeleteTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + client.delete_transfer_job(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_DeleteTransferJob_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_async.py new file mode 100644 index 000000000000..946005c68778 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetAgentPool_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 storage_transfer_v1 + + +async def sample_get_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetAgentPoolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetAgentPool_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_sync.py new file mode 100644 index 000000000000..6ef2fd998757 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_agent_pool_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetAgentPool_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 storage_transfer_v1 + + +def sample_get_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetAgentPoolRequest( + name="name_value", + ) + + # Make the request + response = client.get_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetAgentPool_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_async.py new file mode 100644 index 000000000000..3d7d23ddab61 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_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 storage_transfer_v1 + + +async def sample_get_google_service_account(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetGoogleServiceAccountRequest( + project_id="project_id_value", + ) + + # Make the request + response = await client.get_google_service_account(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_sync.py new file mode 100644 index 000000000000..783de748bd95 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_google_service_account_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGoogleServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_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 storage_transfer_v1 + + +def sample_get_google_service_account(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetGoogleServiceAccountRequest( + project_id="project_id_value", + ) + + # Make the request + response = client.get_google_service_account(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetGoogleServiceAccount_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_async.py new file mode 100644 index 000000000000..70a6e1997817 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetTransferJob_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 storage_transfer_v1 + + +async def sample_get_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = await client.get_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetTransferJob_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_sync.py new file mode 100644 index 000000000000..033399c8374a --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_get_transfer_job_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_GetTransferJob_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 storage_transfer_v1 + + +def sample_get_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.GetTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = client.get_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_GetTransferJob_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_async.py new file mode 100644 index 000000000000..4b989cf3c96f --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAgentPools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ListAgentPools_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 storage_transfer_v1 + + +async def sample_list_agent_pools(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListAgentPoolsRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_agent_pools(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_ListAgentPools_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_sync.py new file mode 100644 index 000000000000..18d2e614b8a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_agent_pools_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAgentPools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ListAgentPools_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 storage_transfer_v1 + + +def sample_list_agent_pools(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListAgentPoolsRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_agent_pools(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_ListAgentPools_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_async.py new file mode 100644 index 000000000000..6b6944a34de9 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTransferJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_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 storage_transfer_v1 + + +async def sample_list_transfer_jobs(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListTransferJobsRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_transfer_jobs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_sync.py new file mode 100644 index 000000000000..5a7702b8b162 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_list_transfer_jobs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTransferJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_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 storage_transfer_v1 + + +def sample_list_transfer_jobs(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ListTransferJobsRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_transfer_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_ListTransferJobs_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_async.py new file mode 100644 index 000000000000..e299dd625d73 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PauseTransferOperation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_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 storage_transfer_v1 + + +async def sample_pause_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.PauseTransferOperationRequest( + name="name_value", + ) + + # Make the request + await client.pause_transfer_operation(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_sync.py new file mode 100644 index 000000000000..d99a6ac41537 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_pause_transfer_operation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PauseTransferOperation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_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 storage_transfer_v1 + + +def sample_pause_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.PauseTransferOperationRequest( + name="name_value", + ) + + # Make the request + client.pause_transfer_operation(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_PauseTransferOperation_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_async.py new file mode 100644 index 000000000000..0218bd5a34a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResumeTransferOperation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_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 storage_transfer_v1 + + +async def sample_resume_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ResumeTransferOperationRequest( + name="name_value", + ) + + # Make the request + await client.resume_transfer_operation(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_sync.py new file mode 100644 index 000000000000..842c1c118494 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_resume_transfer_operation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResumeTransferOperation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_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 storage_transfer_v1 + + +def sample_resume_transfer_operation(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.ResumeTransferOperationRequest( + name="name_value", + ) + + # Make the request + client.resume_transfer_operation(request=request) + + +# [END storagetransfer_v1_generated_StorageTransferService_ResumeTransferOperation_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_async.py new file mode 100644 index 000000000000..dd2219995b13 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_RunTransferJob_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 storage_transfer_v1 + + +async def sample_run_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.RunTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + operation = client.run_transfer_job(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_RunTransferJob_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_sync.py new file mode 100644 index 000000000000..862440e1dab6 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_run_transfer_job_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_RunTransferJob_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 storage_transfer_v1 + + +def sample_run_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.RunTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + operation = client.run_transfer_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_RunTransferJob_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_async.py new file mode 100644 index 000000000000..caec092206b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_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 storage_transfer_v1 + + +async def sample_update_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.UpdateAgentPoolRequest( + agent_pool=agent_pool, + ) + + # Make the request + response = await client.update_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_sync.py new file mode 100644 index 000000000000..3480636a4818 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_agent_pool_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAgentPool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_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 storage_transfer_v1 + + +def sample_update_agent_pool(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + agent_pool = storage_transfer_v1.AgentPool() + agent_pool.name = "name_value" + + request = storage_transfer_v1.UpdateAgentPoolRequest( + agent_pool=agent_pool, + ) + + # Make the request + response = client.update_agent_pool(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_UpdateAgentPool_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_async.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_async.py new file mode 100644 index 000000000000..7bb7d5a97776 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_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 storage_transfer_v1 + + +async def sample_update_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceAsyncClient() + + # Initialize request argument(s) + request = storage_transfer_v1.UpdateTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = await client.update_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_async] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_sync.py b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_sync.py new file mode 100644 index 000000000000..1cf3356a8d61 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/samples/generated_samples/storagetransfer_v1_generated_storage_transfer_service_update_transfer_job_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTransferJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-storage-transfer + + +# [START storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_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 storage_transfer_v1 + + +def sample_update_transfer_job(): + # Create a client + client = storage_transfer_v1.StorageTransferServiceClient() + + # Initialize request argument(s) + request = storage_transfer_v1.UpdateTransferJobRequest( + job_name="job_name_value", + project_id="project_id_value", + ) + + # Make the request + response = client.update_transfer_job(request=request) + + # Handle the response + print(response) + +# [END storagetransfer_v1_generated_StorageTransferService_UpdateTransferJob_sync] diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/scripts/fixup_storage_transfer_v1_keywords.py b/owl-bot-staging/google-cloud-storage-transfer/v1/scripts/fixup_storage_transfer_v1_keywords.py new file mode 100644 index 000000000000..9ab723616023 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/scripts/fixup_storage_transfer_v1_keywords.py @@ -0,0 +1,189 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class storage_transferCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_agent_pool': ('project_id', 'agent_pool', 'agent_pool_id', ), + 'create_transfer_job': ('transfer_job', ), + 'delete_agent_pool': ('name', ), + 'delete_transfer_job': ('job_name', 'project_id', ), + 'get_agent_pool': ('name', ), + 'get_google_service_account': ('project_id', ), + 'get_transfer_job': ('job_name', 'project_id', ), + 'list_agent_pools': ('project_id', 'filter', 'page_size', 'page_token', ), + 'list_transfer_jobs': ('filter', 'page_size', 'page_token', ), + 'pause_transfer_operation': ('name', ), + 'resume_transfer_operation': ('name', ), + 'run_transfer_job': ('job_name', 'project_id', ), + 'update_agent_pool': ('agent_pool', 'update_mask', ), + 'update_transfer_job': ('job_name', 'project_id', 'transfer_job', 'update_transfer_job_field_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=storage_transferCallTransformer(), +): + """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 storage_transfer 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-storage-transfer/v1/setup.py b/owl-bot-staging/google-cloud-storage-transfer/v1/setup.py new file mode 100644 index 000000000000..03d5c5a118ce --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-storage-transfer' + + +description = "Google Cloud Storage Transfer API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/storage_transfer/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/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.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/tests/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/__init__.py b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/test_storage_transfer_service.py b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/test_storage_transfer_service.py new file mode 100644 index 000000000000..f504fb182a54 --- /dev/null +++ b/owl-bot-staging/google-cloud-storage-transfer/v1/tests/unit/gapic/storage_transfer_v1/test_storage_transfer_service.py @@ -0,0 +1,10257 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.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.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.storage_transfer_v1.services.storage_transfer_service import StorageTransferServiceAsyncClient +from google.cloud.storage_transfer_v1.services.storage_transfer_service import StorageTransferServiceClient +from google.cloud.storage_transfer_v1.services.storage_transfer_service import pagers +from google.cloud.storage_transfer_v1.services.storage_transfer_service import transports +from google.cloud.storage_transfer_v1.types import transfer +from google.cloud.storage_transfer_v1.types import transfer_types +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 date_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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert StorageTransferServiceClient._get_default_mtls_endpoint(None) is None + assert StorageTransferServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StorageTransferServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StorageTransferServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StorageTransferServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StorageTransferServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert StorageTransferServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert StorageTransferServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert StorageTransferServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + StorageTransferServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert StorageTransferServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert StorageTransferServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert StorageTransferServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + StorageTransferServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert StorageTransferServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert StorageTransferServiceClient._get_client_cert_source(None, False) is None + assert StorageTransferServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert StorageTransferServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert StorageTransferServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert StorageTransferServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(StorageTransferServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceClient)) +@mock.patch.object(StorageTransferServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = StorageTransferServiceClient._DEFAULT_UNIVERSE + default_endpoint = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert StorageTransferServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert StorageTransferServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == StorageTransferServiceClient.DEFAULT_MTLS_ENDPOINT + assert StorageTransferServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert StorageTransferServiceClient._get_api_endpoint(None, None, default_universe, "always") == StorageTransferServiceClient.DEFAULT_MTLS_ENDPOINT + assert StorageTransferServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == StorageTransferServiceClient.DEFAULT_MTLS_ENDPOINT + assert StorageTransferServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert StorageTransferServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + StorageTransferServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert StorageTransferServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert StorageTransferServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert StorageTransferServiceClient._get_universe_domain(None, None) == StorageTransferServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + StorageTransferServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc"), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StorageTransferServiceClient, "grpc"), + (StorageTransferServiceAsyncClient, "grpc_asyncio"), + (StorageTransferServiceClient, "rest"), +]) +def test_storage_transfer_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'storagetransfer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://storagetransfer.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StorageTransferServiceGrpcTransport, "grpc"), + (transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.StorageTransferServiceRestTransport, "rest"), +]) +def test_storage_transfer_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (StorageTransferServiceClient, "grpc"), + (StorageTransferServiceAsyncClient, "grpc_asyncio"), + (StorageTransferServiceClient, "rest"), +]) +def test_storage_transfer_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'storagetransfer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://storagetransfer.googleapis.com' + ) + + +def test_storage_transfer_service_client_get_transport_class(): + transport = StorageTransferServiceClient.get_transport_class() + available_transports = [ + transports.StorageTransferServiceGrpcTransport, + transports.StorageTransferServiceRestTransport, + ] + assert transport in available_transports + + transport = StorageTransferServiceClient.get_transport_class("grpc") + assert transport == transports.StorageTransferServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc"), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest"), +]) +@mock.patch.object(StorageTransferServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceClient)) +@mock.patch.object(StorageTransferServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceAsyncClient)) +def test_storage_transfer_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StorageTransferServiceClient, '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(StorageTransferServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc", "true"), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc", "false"), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest", "true"), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(StorageTransferServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceClient)) +@mock.patch.object(StorageTransferServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_storage_transfer_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + StorageTransferServiceClient, StorageTransferServiceAsyncClient +]) +@mock.patch.object(StorageTransferServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageTransferServiceClient)) +@mock.patch.object(StorageTransferServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StorageTransferServiceAsyncClient)) +def test_storage_transfer_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + StorageTransferServiceClient, StorageTransferServiceAsyncClient +]) +@mock.patch.object(StorageTransferServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceClient)) +@mock.patch.object(StorageTransferServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(StorageTransferServiceAsyncClient)) +def test_storage_transfer_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = StorageTransferServiceClient._DEFAULT_UNIVERSE + default_endpoint = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = StorageTransferServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc"), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest"), +]) +def test_storage_transfer_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc", grpc_helpers), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (StorageTransferServiceClient, transports.StorageTransferServiceRestTransport, "rest", None), +]) +def test_storage_transfer_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_storage_transfer_service_client_client_options_from_dict(): + with mock.patch('google.cloud.storage_transfer_v1.services.storage_transfer_service.transports.StorageTransferServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StorageTransferServiceClient( + 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", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport, "grpc", grpc_helpers), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_storage_transfer_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "storagetransfer.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="storagetransfer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.GetGoogleServiceAccountRequest, + dict, +]) +def test_get_google_service_account(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.GoogleServiceAccount( + account_email='account_email_value', + subject_id='subject_id_value', + ) + response = client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.GetGoogleServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.GoogleServiceAccount) + assert response.account_email == 'account_email_value' + assert response.subject_id == 'subject_id_value' + + +def test_get_google_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetGoogleServiceAccountRequest() + + +def test_get_google_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.GetGoogleServiceAccountRequest( + project_id='project_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetGoogleServiceAccountRequest( + project_id='project_id_value', + ) + +def test_get_google_service_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_google_service_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_google_service_account] = mock_rpc + request = {} + client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_service_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_google_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.GoogleServiceAccount( + account_email='account_email_value', + subject_id='subject_id_value', + )) + response = await client.get_google_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetGoogleServiceAccountRequest() + +@pytest.mark.asyncio +async def test_get_google_service_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_google_service_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_google_service_account] = mock_rpc + + request = {} + await client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_google_service_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_google_service_account_async(transport: str = 'grpc_asyncio', request_type=transfer.GetGoogleServiceAccountRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.GoogleServiceAccount( + account_email='account_email_value', + subject_id='subject_id_value', + )) + response = await client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.GetGoogleServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.GoogleServiceAccount) + assert response.account_email == 'account_email_value' + assert response.subject_id == 'subject_id_value' + + +@pytest.mark.asyncio +async def test_get_google_service_account_async_from_dict(): + await test_get_google_service_account_async(request_type=dict) + + +def test_get_google_service_account_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetGoogleServiceAccountRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + call.return_value = transfer_types.GoogleServiceAccount() + client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_google_service_account_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetGoogleServiceAccountRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_service_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.GoogleServiceAccount()) + await client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.CreateTransferJobRequest, + dict, +]) +def test_create_transfer_job(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + response = client.create_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.CreateTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +def test_create_transfer_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateTransferJobRequest() + + +def test_create_transfer_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.CreateTransferJobRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_transfer_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateTransferJobRequest( + ) + +def test_create_transfer_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_transfer_job] = mock_rpc + request = {} + client.create_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_transfer_job_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.create_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateTransferJobRequest() + +@pytest.mark.asyncio +async def test_create_transfer_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_transfer_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_transfer_job] = mock_rpc + + request = {} + await client.create_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_transfer_job_async(transport: str = 'grpc_asyncio', request_type=transfer.CreateTransferJobRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.create_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.CreateTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +@pytest.mark.asyncio +async def test_create_transfer_job_async_from_dict(): + await test_create_transfer_job_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + transfer.UpdateTransferJobRequest, + dict, +]) +def test_update_transfer_job(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + response = client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.UpdateTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +def test_update_transfer_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateTransferJobRequest() + + +def test_update_transfer_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.UpdateTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_transfer_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + +def test_update_transfer_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_transfer_job] = mock_rpc + request = {} + client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_transfer_job_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.update_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateTransferJobRequest() + +@pytest.mark.asyncio +async def test_update_transfer_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_transfer_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_transfer_job] = mock_rpc + + request = {} + await client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_transfer_job_async(transport: str = 'grpc_asyncio', request_type=transfer.UpdateTransferJobRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.UpdateTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +@pytest.mark.asyncio +async def test_update_transfer_job_async_from_dict(): + await test_update_transfer_job_async(request_type=dict) + + +def test_update_transfer_job_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.UpdateTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_job), + '__call__') as call: + call.return_value = transfer_types.TransferJob() + client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_transfer_job_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.UpdateTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob()) + await client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.GetTransferJobRequest, + dict, +]) +def test_get_transfer_job(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + response = client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.GetTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +def test_get_transfer_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetTransferJobRequest() + + +def test_get_transfer_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.GetTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_transfer_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + +def test_get_transfer_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_transfer_job] = mock_rpc + request = {} + client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_transfer_job_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.get_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetTransferJobRequest() + +@pytest.mark.asyncio +async def test_get_transfer_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_transfer_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_transfer_job] = mock_rpc + + request = {} + await client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_transfer_job_async(transport: str = 'grpc_asyncio', request_type=transfer.GetTransferJobRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + )) + response = await client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.GetTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + + +@pytest.mark.asyncio +async def test_get_transfer_job_async_from_dict(): + await test_get_transfer_job_async(request_type=dict) + + +def test_get_transfer_job_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_job), + '__call__') as call: + call.return_value = transfer_types.TransferJob() + client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_transfer_job_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.TransferJob()) + await client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.ListTransferJobsRequest, + dict, +]) +def test_list_transfer_jobs(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.ListTransferJobsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transfer_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.ListTransferJobsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferJobsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transfer_jobs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_transfer_jobs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_transfer_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListTransferJobsRequest() + + +def test_list_transfer_jobs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.ListTransferJobsRequest( + filter='filter_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_jobs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_transfer_jobs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListTransferJobsRequest( + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_transfer_jobs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_transfer_jobs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_transfer_jobs] = mock_rpc + request = {} + client.list_transfer_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_transfer_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_transfer_jobs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListTransferJobsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transfer_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListTransferJobsRequest() + +@pytest.mark.asyncio +async def test_list_transfer_jobs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_transfer_jobs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_transfer_jobs] = mock_rpc + + request = {} + await client.list_transfer_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_transfer_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_transfer_jobs_async(transport: str = 'grpc_asyncio', request_type=transfer.ListTransferJobsRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListTransferJobsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transfer_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.ListTransferJobsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferJobsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transfer_jobs_async_from_dict(): + await test_list_transfer_jobs_async(request_type=dict) + + +def test_list_transfer_jobs_pager(transport_name: str = "grpc"): + client = StorageTransferServiceClient( + 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_transfer_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + next_page_token='abc', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[], + next_page_token='def', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + ], + next_page_token='ghi', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_transfer_jobs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, transfer_types.TransferJob) + for i in results) +def test_list_transfer_jobs_pages(transport_name: str = "grpc"): + client = StorageTransferServiceClient( + 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_transfer_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + next_page_token='abc', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[], + next_page_token='def', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + ], + next_page_token='ghi', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transfer_jobs(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_transfer_jobs_async_pager(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + next_page_token='abc', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[], + next_page_token='def', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + ], + next_page_token='ghi', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transfer_jobs(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, transfer_types.TransferJob) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_transfer_jobs_async_pages(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + next_page_token='abc', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[], + next_page_token='def', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + ], + next_page_token='ghi', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + ), + 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_transfer_jobs(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", [ + transfer.PauseTransferOperationRequest, + dict, +]) +def test_pause_transfer_operation(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.PauseTransferOperationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_pause_transfer_operation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.pause_transfer_operation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.PauseTransferOperationRequest() + + +def test_pause_transfer_operation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.PauseTransferOperationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.pause_transfer_operation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.PauseTransferOperationRequest( + name='name_value', + ) + +def test_pause_transfer_operation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.pause_transfer_operation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.pause_transfer_operation] = mock_rpc + request = {} + client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.pause_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_pause_transfer_operation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.pause_transfer_operation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.PauseTransferOperationRequest() + +@pytest.mark.asyncio +async def test_pause_transfer_operation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.pause_transfer_operation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.pause_transfer_operation] = mock_rpc + + request = {} + await client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.pause_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_pause_transfer_operation_async(transport: str = 'grpc_asyncio', request_type=transfer.PauseTransferOperationRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.PauseTransferOperationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_pause_transfer_operation_async_from_dict(): + await test_pause_transfer_operation_async(request_type=dict) + + +def test_pause_transfer_operation_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.PauseTransferOperationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + call.return_value = None + client.pause_transfer_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=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_pause_transfer_operation_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.PauseTransferOperationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_transfer_operation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.ResumeTransferOperationRequest, + dict, +]) +def test_resume_transfer_operation(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.ResumeTransferOperationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_resume_transfer_operation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.resume_transfer_operation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ResumeTransferOperationRequest() + + +def test_resume_transfer_operation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.ResumeTransferOperationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.resume_transfer_operation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ResumeTransferOperationRequest( + name='name_value', + ) + +def test_resume_transfer_operation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.resume_transfer_operation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.resume_transfer_operation] = mock_rpc + request = {} + client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.resume_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_resume_transfer_operation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.resume_transfer_operation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ResumeTransferOperationRequest() + +@pytest.mark.asyncio +async def test_resume_transfer_operation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.resume_transfer_operation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.resume_transfer_operation] = mock_rpc + + request = {} + await client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.resume_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_resume_transfer_operation_async(transport: str = 'grpc_asyncio', request_type=transfer.ResumeTransferOperationRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.ResumeTransferOperationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_resume_transfer_operation_async_from_dict(): + await test_resume_transfer_operation_async(request_type=dict) + + +def test_resume_transfer_operation_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ResumeTransferOperationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + call.return_value = None + client.resume_transfer_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=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_resume_transfer_operation_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ResumeTransferOperationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_transfer_operation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.RunTransferJobRequest, + dict, +]) +def test_run_transfer_job(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.RunTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_transfer_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.RunTransferJobRequest() + + +def test_run_transfer_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.RunTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_transfer_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.RunTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + +def test_run_transfer_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_transfer_job] = mock_rpc + request = {} + client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.run_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_transfer_job_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__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.run_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.RunTransferJobRequest() + +@pytest.mark.asyncio +async def test_run_transfer_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_transfer_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.run_transfer_job] = mock_rpc + + request = {} + await client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_transfer_job_async(transport: str = 'grpc_asyncio', request_type=transfer.RunTransferJobRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__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.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.RunTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_transfer_job_async_from_dict(): + await test_run_transfer_job_async(request_type=dict) + + +def test_run_transfer_job_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.RunTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_transfer_job_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.RunTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_transfer_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.DeleteTransferJobRequest, + dict, +]) +def test_delete_transfer_job(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.DeleteTransferJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_transfer_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteTransferJobRequest() + + +def test_delete_transfer_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.DeleteTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_transfer_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteTransferJobRequest( + job_name='job_name_value', + project_id='project_id_value', + ) + +def test_delete_transfer_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_transfer_job] = mock_rpc + request = {} + client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_transfer_job_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transfer_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteTransferJobRequest() + +@pytest.mark.asyncio +async def test_delete_transfer_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_transfer_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_transfer_job] = mock_rpc + + request = {} + await client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_transfer_job_async(transport: str = 'grpc_asyncio', request_type=transfer.DeleteTransferJobRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transfer_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.DeleteTransferJobRequest() + 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_transfer_job_async_from_dict(): + await test_delete_transfer_job_async(request_type=dict) + + +def test_delete_transfer_job_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.DeleteTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_job), + '__call__') as call: + call.return_value = None + client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_transfer_job_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.DeleteTransferJobRequest() + + request.job_name = 'job_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'job_name=job_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + transfer.CreateAgentPoolRequest, + dict, +]) +def test_create_agent_pool(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + response = client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.CreateAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +def test_create_agent_pool_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateAgentPoolRequest() + + +def test_create_agent_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.CreateAgentPoolRequest( + project_id='project_id_value', + agent_pool_id='agent_pool_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_agent_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateAgentPoolRequest( + project_id='project_id_value', + agent_pool_id='agent_pool_id_value', + ) + +def test_create_agent_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_agent_pool] = mock_rpc + request = {} + client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_agent_pool_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.create_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.CreateAgentPoolRequest() + +@pytest.mark.asyncio +async def test_create_agent_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_agent_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_agent_pool] = mock_rpc + + request = {} + await client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_agent_pool_async(transport: str = 'grpc_asyncio', request_type=transfer.CreateAgentPoolRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.CreateAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +@pytest.mark.asyncio +async def test_create_agent_pool_async_from_dict(): + await test_create_agent_pool_async(request_type=dict) + + +def test_create_agent_pool_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.CreateAgentPoolRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + call.return_value = transfer_types.AgentPool() + client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_agent_pool_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.CreateAgentPoolRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + await client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +def test_create_agent_pool_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_agent_pool( + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_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].project_id + mock_val = 'project_id_value' + assert arg == mock_val + arg = args[0].agent_pool + mock_val = transfer_types.AgentPool(name='name_value') + assert arg == mock_val + arg = args[0].agent_pool_id + mock_val = 'agent_pool_id_value' + assert arg == mock_val + + +def test_create_agent_pool_flattened_error(): + client = StorageTransferServiceClient( + credentials=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_agent_pool( + transfer.CreateAgentPoolRequest(), + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_id_value', + ) + +@pytest.mark.asyncio +async def test_create_agent_pool_flattened_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_agent_pool( + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_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].project_id + mock_val = 'project_id_value' + assert arg == mock_val + arg = args[0].agent_pool + mock_val = transfer_types.AgentPool(name='name_value') + assert arg == mock_val + arg = args[0].agent_pool_id + mock_val = 'agent_pool_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_agent_pool_flattened_error_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_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_agent_pool( + transfer.CreateAgentPoolRequest(), + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.UpdateAgentPoolRequest, + dict, +]) +def test_update_agent_pool(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + response = client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.UpdateAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +def test_update_agent_pool_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateAgentPoolRequest() + + +def test_update_agent_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.UpdateAgentPoolRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_agent_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateAgentPoolRequest( + ) + +def test_update_agent_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_agent_pool] = mock_rpc + request = {} + client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_agent_pool_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.update_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.UpdateAgentPoolRequest() + +@pytest.mark.asyncio +async def test_update_agent_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_agent_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_agent_pool] = mock_rpc + + request = {} + await client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_agent_pool_async(transport: str = 'grpc_asyncio', request_type=transfer.UpdateAgentPoolRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.UpdateAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +@pytest.mark.asyncio +async def test_update_agent_pool_async_from_dict(): + await test_update_agent_pool_async(request_type=dict) + + +def test_update_agent_pool_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.UpdateAgentPoolRequest() + + request.agent_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + call.return_value = transfer_types.AgentPool() + client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent_pool.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_agent_pool_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.UpdateAgentPoolRequest() + + request.agent_pool.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + await client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent_pool.name=name_value', + ) in kw['metadata'] + + +def test_update_agent_pool_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_agent_pool( + agent_pool=transfer_types.AgentPool(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].agent_pool + mock_val = transfer_types.AgentPool(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_agent_pool_flattened_error(): + client = StorageTransferServiceClient( + credentials=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_agent_pool( + transfer.UpdateAgentPoolRequest(), + agent_pool=transfer_types.AgentPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_agent_pool_flattened_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_agent_pool( + agent_pool=transfer_types.AgentPool(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].agent_pool + mock_val = transfer_types.AgentPool(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_agent_pool_flattened_error_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_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_agent_pool( + transfer.UpdateAgentPoolRequest(), + agent_pool=transfer_types.AgentPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.GetAgentPoolRequest, + dict, +]) +def test_get_agent_pool(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + response = client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.GetAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +def test_get_agent_pool_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetAgentPoolRequest() + + +def test_get_agent_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.GetAgentPoolRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_agent_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetAgentPoolRequest( + name='name_value', + ) + +def test_get_agent_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_agent_pool] = mock_rpc + request = {} + client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_agent_pool_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.get_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.GetAgentPoolRequest() + +@pytest.mark.asyncio +async def test_get_agent_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_agent_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_agent_pool] = mock_rpc + + request = {} + await client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_agent_pool_async(transport: str = 'grpc_asyncio', request_type=transfer.GetAgentPoolRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + )) + response = await client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.GetAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + + +@pytest.mark.asyncio +async def test_get_agent_pool_async_from_dict(): + await test_get_agent_pool_async(request_type=dict) + + +def test_get_agent_pool_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetAgentPoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + call.return_value = transfer_types.AgentPool() + client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_pool_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.GetAgentPoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + await client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_pool_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent_pool( + 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_agent_pool_flattened_error(): + client = StorageTransferServiceClient( + credentials=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_agent_pool( + transfer.GetAgentPoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_agent_pool_flattened_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer_types.AgentPool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer_types.AgentPool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent_pool( + 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_agent_pool_flattened_error_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_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_agent_pool( + transfer.GetAgentPoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.ListAgentPoolsRequest, + dict, +]) +def test_list_agent_pools(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.ListAgentPoolsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.ListAgentPoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentPoolsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_agent_pools_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_agent_pools), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_agent_pools() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListAgentPoolsRequest() + + +def test_list_agent_pools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.ListAgentPoolsRequest( + project_id='project_id_value', + filter='filter_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_agent_pools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListAgentPoolsRequest( + project_id='project_id_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_agent_pools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_agent_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_agent_pools] = mock_rpc + request = {} + client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_agent_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_agent_pools_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListAgentPoolsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_agent_pools() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.ListAgentPoolsRequest() + +@pytest.mark.asyncio +async def test_list_agent_pools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_agent_pools in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_agent_pools] = mock_rpc + + request = {} + await client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_agent_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_agent_pools_async(transport: str = 'grpc_asyncio', request_type=transfer.ListAgentPoolsRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListAgentPoolsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.ListAgentPoolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentPoolsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_agent_pools_async_from_dict(): + await test_list_agent_pools_async(request_type=dict) + + +def test_list_agent_pools_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ListAgentPoolsRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + call.return_value = transfer.ListAgentPoolsResponse() + client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_agent_pools_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ListAgentPoolsRequest() + + request.project_id = 'project_id_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListAgentPoolsResponse()) + await client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project_id=project_id_value', + ) in kw['metadata'] + + +def test_list_agent_pools_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.ListAgentPoolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_agent_pools( + project_id='project_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].project_id + mock_val = 'project_id_value' + assert arg == mock_val + + +def test_list_agent_pools_flattened_error(): + client = StorageTransferServiceClient( + credentials=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_agent_pools( + transfer.ListAgentPoolsRequest(), + project_id='project_id_value', + ) + +@pytest.mark.asyncio +async def test_list_agent_pools_flattened_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.ListAgentPoolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.ListAgentPoolsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_agent_pools( + project_id='project_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].project_id + mock_val = 'project_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_agent_pools_flattened_error_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_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_agent_pools( + transfer.ListAgentPoolsRequest(), + project_id='project_id_value', + ) + + +def test_list_agent_pools_pager(transport_name: str = "grpc"): + client = StorageTransferServiceClient( + 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_agent_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + next_page_token='abc', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[], + next_page_token='def', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + ], + next_page_token='ghi', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('project_id', ''), + )), + ) + pager = client.list_agent_pools(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, transfer_types.AgentPool) + for i in results) +def test_list_agent_pools_pages(transport_name: str = "grpc"): + client = StorageTransferServiceClient( + 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_agent_pools), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + next_page_token='abc', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[], + next_page_token='def', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + ], + next_page_token='ghi', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_agent_pools(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_agent_pools_async_pager(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + next_page_token='abc', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[], + next_page_token='def', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + ], + next_page_token='ghi', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_agent_pools(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, transfer_types.AgentPool) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_agent_pools_async_pages(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agent_pools), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + next_page_token='abc', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[], + next_page_token='def', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + ], + next_page_token='ghi', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + ), + 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_agent_pools(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", [ + transfer.DeleteAgentPoolRequest, + dict, +]) +def test_delete_agent_pool(request_type, transport: str = 'grpc'): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.DeleteAgentPoolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_agent_pool_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceClient( + credentials=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_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteAgentPoolRequest() + + +def test_delete_agent_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.DeleteAgentPoolRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_agent_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteAgentPoolRequest( + name='name_value', + ) + +def test_delete_agent_pool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_agent_pool] = mock_rpc + request = {} + client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_agent_pool_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_agent_pool() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transfer.DeleteAgentPoolRequest() + +@pytest.mark.asyncio +async def test_delete_agent_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_agent_pool in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_agent_pool] = mock_rpc + + request = {} + await client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_agent_pool_async(transport: str = 'grpc_asyncio', request_type=transfer.DeleteAgentPoolRequest): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_pool), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.DeleteAgentPoolRequest() + 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_agent_pool_async_from_dict(): + await test_delete_agent_pool_async(request_type=dict) + + +def test_delete_agent_pool_field_headers(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.DeleteAgentPoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__call__') as call: + call.return_value = None + client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_pool_field_headers_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.DeleteAgentPoolRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_pool_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__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_agent_pool( + 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_agent_pool_flattened_error(): + client = StorageTransferServiceClient( + credentials=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_agent_pool( + transfer.DeleteAgentPoolRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_agent_pool_flattened_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent_pool), + '__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_agent_pool( + 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_agent_pool_flattened_error_async(): + client = StorageTransferServiceAsyncClient( + credentials=ga_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_agent_pool( + transfer.DeleteAgentPoolRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.GetGoogleServiceAccountRequest, + dict, +]) +def test_get_google_service_account_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': '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 = transfer_types.GoogleServiceAccount( + account_email='account_email_value', + subject_id='subject_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.GoogleServiceAccount.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_google_service_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.GoogleServiceAccount) + assert response.account_email == 'account_email_value' + assert response.subject_id == 'subject_id_value' + +def test_get_google_service_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_google_service_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_google_service_account] = mock_rpc + + request = {} + client.get_google_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_service_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_google_service_account_rest_required_fields(request_type=transfer.GetGoogleServiceAccountRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_google_service_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_google_service_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.GoogleServiceAccount() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.GoogleServiceAccount.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_google_service_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_google_service_account_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_google_service_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("projectId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_google_service_account_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_get_google_service_account") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_get_google_service_account") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.GetGoogleServiceAccountRequest.pb(transfer.GetGoogleServiceAccountRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.GoogleServiceAccount.to_json(transfer_types.GoogleServiceAccount()) + + request = transfer.GetGoogleServiceAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.GoogleServiceAccount() + + client.get_google_service_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_google_service_account_rest_bad_request(transport: str = 'rest', request_type=transfer.GetGoogleServiceAccountRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_google_service_account(request) + + +def test_get_google_service_account_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.CreateTransferJobRequest, + dict, +]) +def test_create_transfer_job_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["transfer_job"] = {'name': 'name_value', 'description': 'description_value', 'project_id': 'project_id_value', 'transfer_spec': {'gcs_data_sink': {'bucket_name': 'bucket_name_value', 'path': 'path_value', 'managed_folder_transfer_enabled': True}, 'posix_data_sink': {'root_directory': 'root_directory_value'}, 'gcs_data_source': {}, 'aws_s3_data_source': {'bucket_name': 'bucket_name_value', 'aws_access_key': {'access_key_id': 'access_key_id_value', 'secret_access_key': 'secret_access_key_value'}, 'path': 'path_value', 'role_arn': 'role_arn_value', 'cloudfront_domain': 'cloudfront_domain_value', 'credentials_secret': 'credentials_secret_value', 'managed_private_network': True}, 'http_data_source': {'list_url': 'list_url_value'}, 'posix_data_source': {}, 'azure_blob_storage_data_source': {'storage_account': 'storage_account_value', 'azure_credentials': {'sas_token': 'sas_token_value'}, 'container': 'container_value', 'path': 'path_value', 'credentials_secret': 'credentials_secret_value'}, 'aws_s3_compatible_data_source': {'bucket_name': 'bucket_name_value', 'path': 'path_value', 'endpoint': 'endpoint_value', 'region': 'region_value', 's3_metadata': {'auth_method': 1, 'request_model': 1, 'protocol': 1, 'list_api': 1}}, 'hdfs_data_source': {'path': 'path_value'}, 'gcs_intermediate_data_location': {}, 'object_conditions': {'min_time_elapsed_since_last_modification': {'seconds': 751, 'nanos': 543}, 'max_time_elapsed_since_last_modification': {}, 'include_prefixes': ['include_prefixes_value1', 'include_prefixes_value2'], 'exclude_prefixes': ['exclude_prefixes_value1', 'exclude_prefixes_value2'], 'last_modified_since': {'seconds': 751, 'nanos': 543}, 'last_modified_before': {}}, 'transfer_options': {'overwrite_objects_already_existing_in_sink': True, 'delete_objects_unique_in_sink': True, 'delete_objects_from_source_after_transfer': True, 'overwrite_when': 1, 'metadata_options': {'symlink': 1, 'mode': 1, 'gid': 1, 'uid': 1, 'acl': 1, 'storage_class': 1, 'temporary_hold': 1, 'kms_key': 1, 'time_created': 1}}, 'transfer_manifest': {'location': 'location_value'}, 'source_agent_pool_name': 'source_agent_pool_name_value', 'sink_agent_pool_name': 'sink_agent_pool_name_value'}, 'notification_config': {'pubsub_topic': 'pubsub_topic_value', 'event_types': [1], 'payload_format': 1}, 'logging_config': {'log_actions': [1], 'log_action_states': [1], 'enable_onprem_gcs_transfer_logs': True}, 'schedule': {'schedule_start_date': {'year': 433, 'month': 550, 'day': 318}, 'schedule_end_date': {}, 'start_time_of_day': {'hours': 561, 'minutes': 773, 'seconds': 751, 'nanos': 543}, 'end_time_of_day': {}, 'repeat_interval': {}}, 'event_stream': {'name': 'name_value', 'event_stream_start_time': {}, 'event_stream_expiration_time': {}}, 'status': 1, 'creation_time': {}, 'last_modification_time': {}, 'deletion_time': {}, 'latest_operation_name': 'latest_operation_name_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = transfer.CreateTransferJobRequest.meta.fields["transfer_job"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["transfer_job"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["transfer_job"][field])): + del request_init["transfer_job"][field][i][subfield] + else: + del request_init["transfer_job"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + +def test_create_transfer_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_transfer_job] = mock_rpc + + request = {} + client.create_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_transfer_job_rest_required_fields(request_type=transfer.CreateTransferJobRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.TransferJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_transfer_job_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_transfer_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("transferJob", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_transfer_job_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_create_transfer_job") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_create_transfer_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.CreateTransferJobRequest.pb(transfer.CreateTransferJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.TransferJob.to_json(transfer_types.TransferJob()) + + request = transfer.CreateTransferJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.TransferJob() + + client.create_transfer_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_transfer_job_rest_bad_request(transport: str = 'rest', request_type=transfer.CreateTransferJobRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_transfer_job(request) + + +def test_create_transfer_job_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.UpdateTransferJobRequest, + dict, +]) +def test_update_transfer_job_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/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 = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + +def test_update_transfer_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_transfer_job] = mock_rpc + + request = {} + client.update_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_transfer_job_rest_required_fields(request_type=transfer.UpdateTransferJobRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["job_name"] = "" + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["jobName"] = 'job_name_value' + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "jobName" in jsonified_request + assert jsonified_request["jobName"] == 'job_name_value' + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.TransferJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_transfer_job_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_transfer_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("jobName", "projectId", "transferJob", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_transfer_job_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_update_transfer_job") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_update_transfer_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.UpdateTransferJobRequest.pb(transfer.UpdateTransferJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.TransferJob.to_json(transfer_types.TransferJob()) + + request = transfer.UpdateTransferJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.TransferJob() + + client.update_transfer_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_transfer_job_rest_bad_request(transport: str = 'rest', request_type=transfer.UpdateTransferJobRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_transfer_job(request) + + +def test_update_transfer_job_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.GetTransferJobRequest, + dict, +]) +def test_get_transfer_job_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/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 = transfer_types.TransferJob( + name='name_value', + description='description_value', + project_id='project_id_value', + status=transfer_types.TransferJob.Status.ENABLED, + latest_operation_name='latest_operation_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.TransferJob) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.project_id == 'project_id_value' + assert response.status == transfer_types.TransferJob.Status.ENABLED + assert response.latest_operation_name == 'latest_operation_name_value' + +def test_get_transfer_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_transfer_job] = mock_rpc + + request = {} + client.get_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_transfer_job_rest_required_fields(request_type=transfer.GetTransferJobRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["job_name"] = "" + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "projectId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == request_init["project_id"] + + jsonified_request["jobName"] = 'job_name_value' + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_transfer_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("project_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "jobName" in jsonified_request + assert jsonified_request["jobName"] == 'job_name_value' + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.TransferJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.TransferJob.pb(return_value) + 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_transfer_job(request) + + expected_params = [ + ( + "projectId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_transfer_job_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_transfer_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(("projectId", )) & set(("jobName", "projectId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_transfer_job_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_get_transfer_job") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_get_transfer_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.GetTransferJobRequest.pb(transfer.GetTransferJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.TransferJob.to_json(transfer_types.TransferJob()) + + request = transfer.GetTransferJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.TransferJob() + + client.get_transfer_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_transfer_job_rest_bad_request(transport: str = 'rest', request_type=transfer.GetTransferJobRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_transfer_job(request) + + +def test_get_transfer_job_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.ListTransferJobsRequest, + dict, +]) +def test_list_transfer_jobs_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer.ListTransferJobsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer.ListTransferJobsResponse.pb(return_value) + 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_transfer_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferJobsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_transfer_jobs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_transfer_jobs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_transfer_jobs] = mock_rpc + + request = {} + client.list_transfer_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_transfer_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_transfer_jobs_rest_required_fields(request_type=transfer.ListTransferJobsRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "filter" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_transfer_jobs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_transfer_jobs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer.ListTransferJobsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer.ListTransferJobsResponse.pb(return_value) + 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_transfer_jobs(request) + + expected_params = [ + ( + "filter", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_transfer_jobs_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_transfer_jobs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_transfer_jobs_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_list_transfer_jobs") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_list_transfer_jobs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.ListTransferJobsRequest.pb(transfer.ListTransferJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer.ListTransferJobsResponse.to_json(transfer.ListTransferJobsResponse()) + + request = transfer.ListTransferJobsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer.ListTransferJobsResponse() + + client.list_transfer_jobs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_transfer_jobs_rest_bad_request(transport: str = 'rest', request_type=transfer.ListTransferJobsRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_transfer_jobs(request) + + +def test_list_transfer_jobs_rest_pager(transport: str = 'rest'): + client = StorageTransferServiceClient( + 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 = ( + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + next_page_token='abc', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[], + next_page_token='def', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + ], + next_page_token='ghi', + ), + transfer.ListTransferJobsResponse( + transfer_jobs=[ + transfer_types.TransferJob(), + transfer_types.TransferJob(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(transfer.ListTransferJobsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_transfer_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, transfer_types.TransferJob) + for i in results) + + pages = list(client.list_transfer_jobs(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", [ + transfer.PauseTransferOperationRequest, + dict, +]) +def test_pause_transfer_operation_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'transferOperations/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.pause_transfer_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_pause_transfer_operation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.pause_transfer_operation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.pause_transfer_operation] = mock_rpc + + request = {} + client.pause_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.pause_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_pause_transfer_operation_rest_required_fields(request_type=transfer.PauseTransferOperationRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pause_transfer_operation._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()).pause_transfer_operation._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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.pause_transfer_operation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_pause_transfer_operation_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.pause_transfer_operation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_transfer_operation_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_pause_transfer_operation") as pre: + pre.assert_not_called() + pb_message = transfer.PauseTransferOperationRequest.pb(transfer.PauseTransferOperationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = transfer.PauseTransferOperationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.pause_transfer_operation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_pause_transfer_operation_rest_bad_request(transport: str = 'rest', request_type=transfer.PauseTransferOperationRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'transferOperations/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.pause_transfer_operation(request) + + +def test_pause_transfer_operation_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.ResumeTransferOperationRequest, + dict, +]) +def test_resume_transfer_operation_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'transferOperations/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.resume_transfer_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_resume_transfer_operation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.resume_transfer_operation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.resume_transfer_operation] = mock_rpc + + request = {} + client.resume_transfer_operation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.resume_transfer_operation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_resume_transfer_operation_rest_required_fields(request_type=transfer.ResumeTransferOperationRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resume_transfer_operation._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()).resume_transfer_operation._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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.resume_transfer_operation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_resume_transfer_operation_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.resume_transfer_operation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_transfer_operation_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_resume_transfer_operation") as pre: + pre.assert_not_called() + pb_message = transfer.ResumeTransferOperationRequest.pb(transfer.ResumeTransferOperationRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = transfer.ResumeTransferOperationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.resume_transfer_operation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_resume_transfer_operation_rest_bad_request(transport: str = 'rest', request_type=transfer.ResumeTransferOperationRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'transferOperations/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.resume_transfer_operation(request) + + +def test_resume_transfer_operation_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.RunTransferJobRequest, + dict, +]) +def test_run_transfer_job_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/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 = 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.run_transfer_job(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_transfer_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_transfer_job] = mock_rpc + + request = {} + client.run_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.run_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_transfer_job_rest_required_fields(request_type=transfer.RunTransferJobRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["job_name"] = "" + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["jobName"] = 'job_name_value' + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "jobName" in jsonified_request + assert jsonified_request["jobName"] == 'job_name_value' + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + 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.run_transfer_job(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_transfer_job_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_transfer_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("jobName", "projectId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_transfer_job_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(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.StorageTransferServiceRestInterceptor, "post_run_transfer_job") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_run_transfer_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.RunTransferJobRequest.pb(transfer.RunTransferJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = transfer.RunTransferJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_transfer_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_transfer_job_rest_bad_request(transport: str = 'rest', request_type=transfer.RunTransferJobRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_transfer_job(request) + + +def test_run_transfer_job_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.DeleteTransferJobRequest, + dict, +]) +def test_delete_transfer_job_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_transfer_job(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_transfer_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_transfer_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_transfer_job] = mock_rpc + + request = {} + client.delete_transfer_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_transfer_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_transfer_job_rest_required_fields(request_type=transfer.DeleteTransferJobRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["job_name"] = "" + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "projectId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_transfer_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == request_init["project_id"] + + jsonified_request["jobName"] = 'job_name_value' + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_transfer_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("project_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "jobName" in jsonified_request + assert jsonified_request["jobName"] == 'job_name_value' + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + 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_transfer_job(request) + + expected_params = [ + ( + "projectId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_transfer_job_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_transfer_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(("projectId", )) & set(("jobName", "projectId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_transfer_job_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_delete_transfer_job") as pre: + pre.assert_not_called() + pb_message = transfer.DeleteTransferJobRequest.pb(transfer.DeleteTransferJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = transfer.DeleteTransferJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_transfer_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_transfer_job_rest_bad_request(transport: str = 'rest', request_type=transfer.DeleteTransferJobRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'job_name': 'transferJobs/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_transfer_job(request) + + +def test_delete_transfer_job_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.CreateAgentPoolRequest, + dict, +]) +def test_create_agent_pool_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': 'sample1'} + request_init["agent_pool"] = {'name': 'name_value', 'display_name': 'display_name_value', 'state': 1, 'bandwidth_limit': {'limit_mbps': 1072}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = transfer.CreateAgentPoolRequest.meta.fields["agent_pool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["agent_pool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["agent_pool"][field])): + del request_init["agent_pool"][field][i][subfield] + else: + del request_init["agent_pool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + +def test_create_agent_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_agent_pool] = mock_rpc + + request = {} + client.create_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_agent_pool_rest_required_fields(request_type=transfer.CreateAgentPoolRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["project_id"] = "" + request_init["agent_pool_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "agentPoolId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_agent_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "agentPoolId" in jsonified_request + assert jsonified_request["agentPoolId"] == request_init["agent_pool_id"] + + jsonified_request["projectId"] = 'project_id_value' + jsonified_request["agentPoolId"] = 'agent_pool_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_agent_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("agent_pool_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + assert "agentPoolId" in jsonified_request + assert jsonified_request["agentPoolId"] == 'agent_pool_id_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + expected_params = [ + ( + "agentPoolId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_agent_pool_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_agent_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("agentPoolId", )) & set(("projectId", "agentPool", "agentPoolId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_agent_pool_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_create_agent_pool") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_create_agent_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.CreateAgentPoolRequest.pb(transfer.CreateAgentPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.AgentPool.to_json(transfer_types.AgentPool()) + + request = transfer.CreateAgentPoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.AgentPool() + + client.create_agent_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_agent_pool_rest_bad_request(transport: str = 'rest', request_type=transfer.CreateAgentPoolRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_agent_pool(request) + + +def test_create_agent_pool_rest_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + + # get arguments that satisfy an http rule for this method + sample_request = {'project_id': 'sample1'} + + # get truthy value for each flattened field + mock_args = dict( + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_agent_pool(**mock_args) + + # Establish that the underlying call 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/projects/{project_id=*}/agentPools" % client.transport._host, args[1]) + + +def test_create_agent_pool_rest_flattened_error(transport: str = 'rest'): + client = StorageTransferServiceClient( + credentials=ga_credentials.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_agent_pool( + transfer.CreateAgentPoolRequest(), + project_id='project_id_value', + agent_pool=transfer_types.AgentPool(name='name_value'), + agent_pool_id='agent_pool_id_value', + ) + + +def test_create_agent_pool_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.UpdateAgentPoolRequest, + dict, +]) +def test_update_agent_pool_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'agent_pool': {'name': 'projects/sample1/agentPools/sample2'}} + request_init["agent_pool"] = {'name': 'projects/sample1/agentPools/sample2', 'display_name': 'display_name_value', 'state': 1, 'bandwidth_limit': {'limit_mbps': 1072}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = transfer.UpdateAgentPoolRequest.meta.fields["agent_pool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["agent_pool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["agent_pool"][field])): + del request_init["agent_pool"][field][i][subfield] + else: + del request_init["agent_pool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + +def test_update_agent_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_agent_pool] = mock_rpc + + request = {} + client.update_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_agent_pool_rest_required_fields(request_type=transfer.UpdateAgentPoolRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_agent_pool._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_agent_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_agent_pool_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_agent_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("agentPool", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_agent_pool_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_update_agent_pool") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_update_agent_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.UpdateAgentPoolRequest.pb(transfer.UpdateAgentPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.AgentPool.to_json(transfer_types.AgentPool()) + + request = transfer.UpdateAgentPoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.AgentPool() + + client.update_agent_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_agent_pool_rest_bad_request(transport: str = 'rest', request_type=transfer.UpdateAgentPoolRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'agent_pool': {'name': 'projects/sample1/agentPools/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_agent_pool(request) + + +def test_update_agent_pool_rest_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + + # get arguments that satisfy an http rule for this method + sample_request = {'agent_pool': {'name': 'projects/sample1/agentPools/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + agent_pool=transfer_types.AgentPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_agent_pool(**mock_args) + + # Establish that the underlying call 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/{agent_pool.name=projects/*/agentPools/*}" % client.transport._host, args[1]) + + +def test_update_agent_pool_rest_flattened_error(transport: str = 'rest'): + client = StorageTransferServiceClient( + credentials=ga_credentials.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_agent_pool( + transfer.UpdateAgentPoolRequest(), + agent_pool=transfer_types.AgentPool(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_agent_pool_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.GetAgentPoolRequest, + dict, +]) +def test_get_agent_pool_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/agentPools/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 = transfer_types.AgentPool( + name='name_value', + display_name='display_name_value', + state=transfer_types.AgentPool.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer_types.AgentPool) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == transfer_types.AgentPool.State.CREATING + +def test_get_agent_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_agent_pool] = mock_rpc + + request = {} + client.get_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_agent_pool_rest_required_fields(request_type=transfer.GetAgentPoolRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_agent_pool._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_agent_pool._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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + 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_agent_pool(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_agent_pool_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_agent_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_agent_pool_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_get_agent_pool") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_get_agent_pool") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.GetAgentPoolRequest.pb(transfer.GetAgentPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer_types.AgentPool.to_json(transfer_types.AgentPool()) + + request = transfer.GetAgentPoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer_types.AgentPool() + + client.get_agent_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_agent_pool_rest_bad_request(transport: str = 'rest', request_type=transfer.GetAgentPoolRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/agentPools/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_agent_pool(request) + + +def test_get_agent_pool_rest_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer_types.AgentPool() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/agentPools/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer_types.AgentPool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_agent_pool(**mock_args) + + # Establish that the underlying call 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/*/agentPools/*}" % client.transport._host, args[1]) + + +def test_get_agent_pool_rest_flattened_error(transport: str = 'rest'): + client = StorageTransferServiceClient( + credentials=ga_credentials.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_agent_pool( + transfer.GetAgentPoolRequest(), + name='name_value', + ) + + +def test_get_agent_pool_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + transfer.ListAgentPoolsRequest, + dict, +]) +def test_list_agent_pools_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': '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 = transfer.ListAgentPoolsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer.ListAgentPoolsResponse.pb(return_value) + 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_agent_pools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentPoolsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_agent_pools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_agent_pools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_agent_pools] = mock_rpc + + request = {} + client.list_agent_pools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_agent_pools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_agent_pools_rest_required_fields(request_type=transfer.ListAgentPoolsRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["project_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_agent_pools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["projectId"] = 'project_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_agent_pools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "projectId" in jsonified_request + assert jsonified_request["projectId"] == 'project_id_value' + + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = transfer.ListAgentPoolsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = transfer.ListAgentPoolsResponse.pb(return_value) + 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_agent_pools(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_agent_pools_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_agent_pools._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("projectId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_agent_pools_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "post_list_agent_pools") as post, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_list_agent_pools") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = transfer.ListAgentPoolsRequest.pb(transfer.ListAgentPoolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = transfer.ListAgentPoolsResponse.to_json(transfer.ListAgentPoolsResponse()) + + request = transfer.ListAgentPoolsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = transfer.ListAgentPoolsResponse() + + client.list_agent_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_agent_pools_rest_bad_request(transport: str = 'rest', request_type=transfer.ListAgentPoolsRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'project_id': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_agent_pools(request) + + +def test_list_agent_pools_rest_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = transfer.ListAgentPoolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'project_id': 'sample1'} + + # get truthy value for each flattened field + mock_args = dict( + project_id='project_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = transfer.ListAgentPoolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_agent_pools(**mock_args) + + # Establish that the underlying call 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/projects/{project_id=*}/agentPools" % client.transport._host, args[1]) + + +def test_list_agent_pools_rest_flattened_error(transport: str = 'rest'): + client = StorageTransferServiceClient( + credentials=ga_credentials.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_agent_pools( + transfer.ListAgentPoolsRequest(), + project_id='project_id_value', + ) + + +def test_list_agent_pools_rest_pager(transport: str = 'rest'): + client = StorageTransferServiceClient( + 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 = ( + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + next_page_token='abc', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[], + next_page_token='def', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + ], + next_page_token='ghi', + ), + transfer.ListAgentPoolsResponse( + agent_pools=[ + transfer_types.AgentPool(), + transfer_types.AgentPool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(transfer.ListAgentPoolsResponse.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 = {'project_id': 'sample1'} + + pager = client.list_agent_pools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, transfer_types.AgentPool) + for i in results) + + pages = list(client.list_agent_pools(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", [ + transfer.DeleteAgentPoolRequest, + dict, +]) +def test_delete_agent_pool_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/agentPools/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_agent_pool(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_agent_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_agent_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_agent_pool] = mock_rpc + + request = {} + client.delete_agent_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_agent_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_agent_pool_rest_required_fields(request_type=transfer.DeleteAgentPoolRequest): + transport_class = transports.StorageTransferServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_agent_pool._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_agent_pool._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 = StorageTransferServiceClient( + 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_agent_pool(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_agent_pool_rest_unset_required_fields(): + transport = transports.StorageTransferServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_agent_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_agent_pool_rest_interceptors(null_interceptor): + transport = transports.StorageTransferServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.StorageTransferServiceRestInterceptor(), + ) + client = StorageTransferServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.StorageTransferServiceRestInterceptor, "pre_delete_agent_pool") as pre: + pre.assert_not_called() + pb_message = transfer.DeleteAgentPoolRequest.pb(transfer.DeleteAgentPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "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 = transfer.DeleteAgentPoolRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_agent_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_agent_pool_rest_bad_request(transport: str = 'rest', request_type=transfer.DeleteAgentPoolRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/agentPools/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_agent_pool(request) + + +def test_delete_agent_pool_rest_flattened(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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/agentPools/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_agent_pool(**mock_args) + + # Establish that the underlying call 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/*/agentPools/*}" % client.transport._host, args[1]) + + +def test_delete_agent_pool_rest_flattened_error(transport: str = 'rest'): + client = StorageTransferServiceClient( + credentials=ga_credentials.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_agent_pool( + transfer.DeleteAgentPoolRequest(), + name='name_value', + ) + + +def test_delete_agent_pool_rest_error(): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageTransferServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StorageTransferServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StorageTransferServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageTransferServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StorageTransferServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StorageTransferServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StorageTransferServiceGrpcTransport, + transports.StorageTransferServiceGrpcAsyncIOTransport, + transports.StorageTransferServiceRestTransport, +]) +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 = StorageTransferServiceClient.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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StorageTransferServiceGrpcTransport, + ) + +def test_storage_transfer_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StorageTransferServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_storage_transfer_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.storage_transfer_v1.services.storage_transfer_service.transports.StorageTransferServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StorageTransferServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_google_service_account', + 'create_transfer_job', + 'update_transfer_job', + 'get_transfer_job', + 'list_transfer_jobs', + 'pause_transfer_operation', + 'resume_transfer_operation', + 'run_transfer_job', + 'delete_transfer_job', + 'create_agent_pool', + 'update_agent_pool', + 'get_agent_pool', + 'list_agent_pools', + 'delete_agent_pool', + 'get_operation', + 'cancel_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_storage_transfer_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.storage_transfer_v1.services.storage_transfer_service.transports.StorageTransferServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StorageTransferServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_storage_transfer_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.storage_transfer_v1.services.storage_transfer_service.transports.StorageTransferServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StorageTransferServiceTransport() + adc.assert_called_once() + + +def test_storage_transfer_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StorageTransferServiceClient() + 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.StorageTransferServiceGrpcTransport, + transports.StorageTransferServiceGrpcAsyncIOTransport, + ], +) +def test_storage_transfer_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StorageTransferServiceGrpcTransport, + transports.StorageTransferServiceGrpcAsyncIOTransport, + transports.StorageTransferServiceRestTransport, + ], +) +def test_storage_transfer_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StorageTransferServiceGrpcTransport, grpc_helpers), + (transports.StorageTransferServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_storage_transfer_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "storagetransfer.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="storagetransfer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StorageTransferServiceGrpcTransport, transports.StorageTransferServiceGrpcAsyncIOTransport]) +def test_storage_transfer_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_storage_transfer_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.StorageTransferServiceRestTransport ( + 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_storage_transfer_service_rest_lro_client(): + client = StorageTransferServiceClient( + 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_storage_transfer_service_host_no_port(transport_name): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='storagetransfer.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'storagetransfer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://storagetransfer.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_storage_transfer_service_host_with_port(transport_name): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='storagetransfer.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'storagetransfer.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://storagetransfer.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_storage_transfer_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = StorageTransferServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = StorageTransferServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_google_service_account._session + session2 = client2.transport.get_google_service_account._session + assert session1 != session2 + session1 = client1.transport.create_transfer_job._session + session2 = client2.transport.create_transfer_job._session + assert session1 != session2 + session1 = client1.transport.update_transfer_job._session + session2 = client2.transport.update_transfer_job._session + assert session1 != session2 + session1 = client1.transport.get_transfer_job._session + session2 = client2.transport.get_transfer_job._session + assert session1 != session2 + session1 = client1.transport.list_transfer_jobs._session + session2 = client2.transport.list_transfer_jobs._session + assert session1 != session2 + session1 = client1.transport.pause_transfer_operation._session + session2 = client2.transport.pause_transfer_operation._session + assert session1 != session2 + session1 = client1.transport.resume_transfer_operation._session + session2 = client2.transport.resume_transfer_operation._session + assert session1 != session2 + session1 = client1.transport.run_transfer_job._session + session2 = client2.transport.run_transfer_job._session + assert session1 != session2 + session1 = client1.transport.delete_transfer_job._session + session2 = client2.transport.delete_transfer_job._session + assert session1 != session2 + session1 = client1.transport.create_agent_pool._session + session2 = client2.transport.create_agent_pool._session + assert session1 != session2 + session1 = client1.transport.update_agent_pool._session + session2 = client2.transport.update_agent_pool._session + assert session1 != session2 + session1 = client1.transport.get_agent_pool._session + session2 = client2.transport.get_agent_pool._session + assert session1 != session2 + session1 = client1.transport.list_agent_pools._session + session2 = client2.transport.list_agent_pools._session + assert session1 != session2 + session1 = client1.transport.delete_agent_pool._session + session2 = client2.transport.delete_agent_pool._session + assert session1 != session2 +def test_storage_transfer_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StorageTransferServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_storage_transfer_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StorageTransferServiceGrpcAsyncIOTransport( + 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.StorageTransferServiceGrpcTransport, transports.StorageTransferServiceGrpcAsyncIOTransport]) +def test_storage_transfer_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StorageTransferServiceGrpcTransport, transports.StorageTransferServiceGrpcAsyncIOTransport]) +def test_storage_transfer_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_storage_transfer_service_grpc_lro_client(): + client = StorageTransferServiceClient( + 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_storage_transfer_service_grpc_lro_async_client(): + client = StorageTransferServiceAsyncClient( + 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_agent_pools_path(): + project_id = "squid" + agent_pool_id = "clam" + expected = "projects/{project_id}/agentPools/{agent_pool_id}".format(project_id=project_id, agent_pool_id=agent_pool_id, ) + actual = StorageTransferServiceClient.agent_pools_path(project_id, agent_pool_id) + assert expected == actual + + +def test_parse_agent_pools_path(): + expected = { + "project_id": "whelk", + "agent_pool_id": "octopus", + } + path = StorageTransferServiceClient.agent_pools_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.parse_agent_pools_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StorageTransferServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = StorageTransferServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = StorageTransferServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = StorageTransferServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StorageTransferServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = StorageTransferServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = StorageTransferServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = StorageTransferServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StorageTransferServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = StorageTransferServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StorageTransferServiceClient.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.StorageTransferServiceTransport, '_prep_wrapped_messages') as prep: + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StorageTransferServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StorageTransferServiceClient.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 = StorageTransferServiceAsyncClient( + 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'transferOperations/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.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'transferOperations/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'transferOperations/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.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'transferOperations/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 = 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'transferOperations'}, 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'transferOperations'} + request = request_type(**request_init) + # Mock the http request call within the method and 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_cancel_operation(transport: str = "grpc"): + client = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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_asyncio"): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceClient( + 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 = StorageTransferServiceAsyncClient( + 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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_asyncio"): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceClient( + 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 = StorageTransferServiceAsyncClient( + 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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_asyncio"): + client = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = StorageTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = StorageTransferServiceClient( + 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 = StorageTransferServiceAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StorageTransferServiceClient( + 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 = StorageTransferServiceClient( + 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", [ + (StorageTransferServiceClient, transports.StorageTransferServiceGrpcTransport), + (StorageTransferServiceAsyncClient, transports.StorageTransferServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )