From b023c0e897a63be9ad1f8dfab0ff2e0e767aa656 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 19 Aug 2021 16:34:39 +0000 Subject: [PATCH 1/2] docs: Improvements to various message and field descriptions PiperOrigin-RevId: 391604499 Source-Link: https://github.com/googleapis/googleapis/commit/853cfd33b66580be0b61f3bb0cfea4abd351b565 Source-Link: https://github.com/googleapis/googleapis-gen/commit/512fb8186918c378b941d41bd27f2fc19b5afd39 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../data_transfer_service.rst | 10 + .../bigquery_datatransfer_v1/services.rst | 6 + .../docs/bigquery_datatransfer_v1/types.rst | 7 + owl-bot-staging/v1/docs/conf.py | 376 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../cloud/bigquery_datatransfer/__init__.py | 83 + .../cloud/bigquery_datatransfer/py.typed | 2 + .../bigquery_datatransfer_v1/__init__.py | 84 + .../gapic_metadata.json | 163 + .../cloud/bigquery_datatransfer_v1/py.typed | 2 + .../services/__init__.py | 15 + .../data_transfer_service/__init__.py | 22 + .../data_transfer_service/async_client.py | 1432 +++++ .../services/data_transfer_service/client.py | 1572 +++++ .../services/data_transfer_service/pagers.py | 507 ++ .../transports/__init__.py | 33 + .../data_transfer_service/transports/base.py | 422 ++ .../data_transfer_service/transports/grpc.py | 615 ++ .../transports/grpc_asyncio.py | 619 ++ .../types/__init__.py | 82 + .../types/datatransfer.py | 1023 ++++ .../types/transfer.py | 442 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + ...fixup_bigquery_datatransfer_v1_keywords.py | 189 + owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../bigquery_datatransfer_v1/__init__.py | 16 + .../test_data_transfer_service.py | 5087 +++++++++++++++++ 34 files changed, 13121 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst create mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py create mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..63daceaf --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/bigquery_datatransfer/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..c429b83c --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/bigquery_datatransfer *.py +recursive-include google/cloud/bigquery_datatransfer_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..a68e336f --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Bigquery Datatransfer 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 Bigquery Datatransfer API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst new file mode 100644 index 00000000..480f43ed --- /dev/null +++ b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst @@ -0,0 +1,10 @@ +DataTransferService +------------------------------------- + +.. automodule:: google.cloud.bigquery_datatransfer_v1.services.data_transfer_service + :members: + :inherited-members: + +.. automodule:: google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst new file mode 100644 index 00000000..37a71a43 --- /dev/null +++ b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Bigquery Datatransfer v1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + data_transfer_service diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst new file mode 100644 index 00000000..d46636eb --- /dev/null +++ b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Bigquery Datatransfer v1 API +=================================================== + +.. automodule:: google.cloud.bigquery_datatransfer_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..7ff9493b --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-bigquery-datatransfer 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-bigquery-datatransfer" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-bigquery-datatransfer-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 = [ + ( + master_doc, + "google-cloud-bigquery-datatransfer.tex", + u"google-cloud-bigquery-datatransfer 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 = [ + ( + master_doc, + "google-cloud-bigquery-datatransfer", + u"Google Cloud Bigquery Datatransfer 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 = [ + ( + master_doc, + "google-cloud-bigquery-datatransfer", + u"google-cloud-bigquery-datatransfer Documentation", + author, + "google-cloud-bigquery-datatransfer", + "GAPIC library for Google Cloud Bigquery Datatransfer API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..3bc1adcc --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + bigquery_datatransfer_v1/services + bigquery_datatransfer_v1/types diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py new file mode 100644 index 00000000..f364f477 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py @@ -0,0 +1,83 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.bigquery_datatransfer_v1.services.data_transfer_service.client import DataTransferServiceClient +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.async_client import DataTransferServiceAsyncClient + +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CheckValidCredsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CheckValidCredsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CreateTransferConfigRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DataSource +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DataSourceParameter +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DeleteTransferConfigRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DeleteTransferRunRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetDataSourceRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetTransferConfigRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetTransferRunRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListDataSourcesRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListDataSourcesResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferConfigsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferConfigsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferLogsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferLogsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferRunsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferRunsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ScheduleTransferRunsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ScheduleTransferRunsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import StartManualTransferRunsRequest +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import StartManualTransferRunsResponse +from google.cloud.bigquery_datatransfer_v1.types.datatransfer import UpdateTransferConfigRequest +from google.cloud.bigquery_datatransfer_v1.types.transfer import EmailPreferences +from google.cloud.bigquery_datatransfer_v1.types.transfer import ScheduleOptions +from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferConfig +from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferMessage +from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferRun +from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferState +from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferType + +__all__ = ('DataTransferServiceClient', + 'DataTransferServiceAsyncClient', + 'CheckValidCredsRequest', + 'CheckValidCredsResponse', + 'CreateTransferConfigRequest', + 'DataSource', + 'DataSourceParameter', + 'DeleteTransferConfigRequest', + 'DeleteTransferRunRequest', + 'GetDataSourceRequest', + 'GetTransferConfigRequest', + 'GetTransferRunRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'ListTransferConfigsRequest', + 'ListTransferConfigsResponse', + 'ListTransferLogsRequest', + 'ListTransferLogsResponse', + 'ListTransferRunsRequest', + 'ListTransferRunsResponse', + 'ScheduleTransferRunsRequest', + 'ScheduleTransferRunsResponse', + 'StartManualTransferRunsRequest', + 'StartManualTransferRunsResponse', + 'UpdateTransferConfigRequest', + 'EmailPreferences', + 'ScheduleOptions', + 'TransferConfig', + 'TransferMessage', + 'TransferRun', + 'TransferState', + 'TransferType', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed new file mode 100644 index 00000000..1bd9d383 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-bigquery-datatransfer package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py new file mode 100644 index 00000000..b93e0e2b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py @@ -0,0 +1,84 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.data_transfer_service import DataTransferServiceClient +from .services.data_transfer_service import DataTransferServiceAsyncClient + +from .types.datatransfer import CheckValidCredsRequest +from .types.datatransfer import CheckValidCredsResponse +from .types.datatransfer import CreateTransferConfigRequest +from .types.datatransfer import DataSource +from .types.datatransfer import DataSourceParameter +from .types.datatransfer import DeleteTransferConfigRequest +from .types.datatransfer import DeleteTransferRunRequest +from .types.datatransfer import GetDataSourceRequest +from .types.datatransfer import GetTransferConfigRequest +from .types.datatransfer import GetTransferRunRequest +from .types.datatransfer import ListDataSourcesRequest +from .types.datatransfer import ListDataSourcesResponse +from .types.datatransfer import ListTransferConfigsRequest +from .types.datatransfer import ListTransferConfigsResponse +from .types.datatransfer import ListTransferLogsRequest +from .types.datatransfer import ListTransferLogsResponse +from .types.datatransfer import ListTransferRunsRequest +from .types.datatransfer import ListTransferRunsResponse +from .types.datatransfer import ScheduleTransferRunsRequest +from .types.datatransfer import ScheduleTransferRunsResponse +from .types.datatransfer import StartManualTransferRunsRequest +from .types.datatransfer import StartManualTransferRunsResponse +from .types.datatransfer import UpdateTransferConfigRequest +from .types.transfer import EmailPreferences +from .types.transfer import ScheduleOptions +from .types.transfer import TransferConfig +from .types.transfer import TransferMessage +from .types.transfer import TransferRun +from .types.transfer import TransferState +from .types.transfer import TransferType + +__all__ = ( + 'DataTransferServiceAsyncClient', +'CheckValidCredsRequest', +'CheckValidCredsResponse', +'CreateTransferConfigRequest', +'DataSource', +'DataSourceParameter', +'DataTransferServiceClient', +'DeleteTransferConfigRequest', +'DeleteTransferRunRequest', +'EmailPreferences', +'GetDataSourceRequest', +'GetTransferConfigRequest', +'GetTransferRunRequest', +'ListDataSourcesRequest', +'ListDataSourcesResponse', +'ListTransferConfigsRequest', +'ListTransferConfigsResponse', +'ListTransferLogsRequest', +'ListTransferLogsResponse', +'ListTransferRunsRequest', +'ListTransferRunsResponse', +'ScheduleOptions', +'ScheduleTransferRunsRequest', +'ScheduleTransferRunsResponse', +'StartManualTransferRunsRequest', +'StartManualTransferRunsResponse', +'TransferConfig', +'TransferMessage', +'TransferRun', +'TransferState', +'TransferType', +'UpdateTransferConfigRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json new file mode 100644 index 00000000..75ee9340 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json @@ -0,0 +1,163 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.bigquery_datatransfer_v1", + "protoPackage": "google.cloud.bigquery.datatransfer.v1", + "schema": "1.0", + "services": { + "DataTransferService": { + "clients": { + "grpc": { + "libraryClient": "DataTransferServiceClient", + "rpcs": { + "CheckValidCreds": { + "methods": [ + "check_valid_creds" + ] + }, + "CreateTransferConfig": { + "methods": [ + "create_transfer_config" + ] + }, + "DeleteTransferConfig": { + "methods": [ + "delete_transfer_config" + ] + }, + "DeleteTransferRun": { + "methods": [ + "delete_transfer_run" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "GetTransferConfig": { + "methods": [ + "get_transfer_config" + ] + }, + "GetTransferRun": { + "methods": [ + "get_transfer_run" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "ListTransferConfigs": { + "methods": [ + "list_transfer_configs" + ] + }, + "ListTransferLogs": { + "methods": [ + "list_transfer_logs" + ] + }, + "ListTransferRuns": { + "methods": [ + "list_transfer_runs" + ] + }, + "ScheduleTransferRuns": { + "methods": [ + "schedule_transfer_runs" + ] + }, + "StartManualTransferRuns": { + "methods": [ + "start_manual_transfer_runs" + ] + }, + "UpdateTransferConfig": { + "methods": [ + "update_transfer_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataTransferServiceAsyncClient", + "rpcs": { + "CheckValidCreds": { + "methods": [ + "check_valid_creds" + ] + }, + "CreateTransferConfig": { + "methods": [ + "create_transfer_config" + ] + }, + "DeleteTransferConfig": { + "methods": [ + "delete_transfer_config" + ] + }, + "DeleteTransferRun": { + "methods": [ + "delete_transfer_run" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "GetTransferConfig": { + "methods": [ + "get_transfer_config" + ] + }, + "GetTransferRun": { + "methods": [ + "get_transfer_run" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "ListTransferConfigs": { + "methods": [ + "list_transfer_configs" + ] + }, + "ListTransferLogs": { + "methods": [ + "list_transfer_logs" + ] + }, + "ListTransferRuns": { + "methods": [ + "list_transfer_runs" + ] + }, + "ScheduleTransferRuns": { + "methods": [ + "schedule_transfer_runs" + ] + }, + "StartManualTransferRuns": { + "methods": [ + "start_manual_transfer_runs" + ] + }, + "UpdateTransferConfig": { + "methods": [ + "update_transfer_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed new file mode 100644 index 00000000..1bd9d383 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-bigquery-datatransfer package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py new file mode 100644 index 00000000..920fa888 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DataTransferServiceClient +from .async_client import DataTransferServiceAsyncClient + +__all__ = ( + 'DataTransferServiceClient', + 'DataTransferServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py new file mode 100644 index 00000000..32c0261d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py @@ -0,0 +1,1432 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources +import warnings + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport +from .client import DataTransferServiceClient + + +class DataTransferServiceAsyncClient: + """The Google BigQuery Data Transfer Service API enables + BigQuery users to configure the transfer of their data from + other Google Products into BigQuery. This service contains + methods that are end user exposed. It backs up the frontend. + """ + + _client: DataTransferServiceClient + + DEFAULT_ENDPOINT = DataTransferServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataTransferServiceClient.DEFAULT_MTLS_ENDPOINT + + data_source_path = staticmethod(DataTransferServiceClient.data_source_path) + parse_data_source_path = staticmethod(DataTransferServiceClient.parse_data_source_path) + run_path = staticmethod(DataTransferServiceClient.run_path) + parse_run_path = staticmethod(DataTransferServiceClient.parse_run_path) + transfer_config_path = staticmethod(DataTransferServiceClient.transfer_config_path) + parse_transfer_config_path = staticmethod(DataTransferServiceClient.parse_transfer_config_path) + common_billing_account_path = staticmethod(DataTransferServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataTransferServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataTransferServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DataTransferServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DataTransferServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DataTransferServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DataTransferServiceClient.common_project_path) + parse_common_project_path = staticmethod(DataTransferServiceClient.parse_common_project_path) + common_location_path = staticmethod(DataTransferServiceClient.common_location_path) + parse_common_location_path = staticmethod(DataTransferServiceClient.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: + DataTransferServiceAsyncClient: The constructed client. + """ + return DataTransferServiceClient.from_service_account_info.__func__(DataTransferServiceAsyncClient, 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: + DataTransferServiceAsyncClient: The constructed client. + """ + return DataTransferServiceClient.from_service_account_file.__func__(DataTransferServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DataTransferServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataTransferServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataTransferServiceClient).get_transport_class, type(DataTransferServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DataTransferServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data 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 (Union[str, ~.DataTransferServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DataTransferServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_data_source(self, + request: datatransfer.GetDataSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.DataSource: + r"""Retrieves a supported data source and returns its + settings, which can be used for UI rendering. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetDataSourceRequest`): + The request object. A request to get data source info. + name (:class:`str`): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/dataSources/{data_source_id}`` + or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.DataSource: + Represents data source metadata. + Metadata is sufficient to render UI and + request proper OAuth tokens. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.GetDataSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_data_source, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_sources(self, + request: datatransfer.ListDataSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSourcesAsyncPager: + r"""Lists supported data sources and returns their + settings, which can be used for UI rendering. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesRequest`): + The request object. Request to list supported data + sources and their data transfer settings. + parent (:class:`str`): + Required. The BigQuery project id for which data sources + should be returned. Must be in the form: + ``projects/{project_id}`` or + \`projects/{project_id}/locations/{location_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListDataSourcesAsyncPager: + Returns list of supported data + sources and their metadata. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.ListDataSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_data_sources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataSourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_transfer_config(self, + request: datatransfer.CreateTransferConfigRequest = None, + *, + parent: str = None, + transfer_config: transfer.TransferConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Creates a new data transfer configuration. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.CreateTransferConfigRequest`): + The request object. A request to create a data transfer + configuration. If new credentials are needed for this + transfer configuration, an authorization code must be + provided. If an authorization code is provided, the + transfer configuration will be associated with the user + id corresponding to the authorization code. Otherwise, + the transfer configuration will be associated with the + calling user. + parent (:class:`str`): + Required. The BigQuery project id where the transfer + configuration should be created. Must be in the format + projects/{project_id}/locations/{location_id} or + projects/{project_id}. If specified location and + location of the destination bigquery dataset do not + match - the request will fail. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transfer_config (:class:`google.cloud.bigquery_datatransfer_v1.types.TransferConfig`): + Required. Data transfer configuration + to create. + + This corresponds to the ``transfer_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transfer_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.CreateTransferConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transfer_config is not None: + request.transfer_config = transfer_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_transfer_config, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_transfer_config(self, + request: datatransfer.UpdateTransferConfigRequest = None, + *, + transfer_config: transfer.TransferConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Updates a data transfer configuration. + All fields must be set, even if they are not updated. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.UpdateTransferConfigRequest`): + The request object. A request to update a transfer + configuration. To update the user id of the transfer + configuration, an authorization code needs to be + provided. + transfer_config (:class:`google.cloud.bigquery_datatransfer_v1.types.TransferConfig`): + Required. Data transfer configuration + to create. + + This corresponds to the ``transfer_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Required list of fields to + be updated in this request. + + 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.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transfer_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.UpdateTransferConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transfer_config is not None: + request.transfer_config = transfer_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_transfer_config, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transfer_config.name", request.transfer_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_transfer_config(self, + request: datatransfer.DeleteTransferConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a data transfer configuration, + including any associated transfer runs and logs. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.DeleteTransferConfigRequest`): + The request object. A request to delete data transfer + information. All associated transfer runs and log + messages will be deleted as well. + name (:class:`str`): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.DeleteTransferConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_transfer_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_transfer_config(self, + request: datatransfer.GetTransferConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Returns information about a data transfer config. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetTransferConfigRequest`): + The request object. A request to get data transfer + information. + name (:class:`str`): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.GetTransferConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_transfer_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_transfer_configs(self, + request: datatransfer.ListTransferConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferConfigsAsyncPager: + r"""Returns information about all transfer configs owned + by a project in the specified location. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest`): + The request object. A request to list data transfers + configured for a BigQuery project. + parent (:class:`str`): + Required. The BigQuery project id for which data sources + should be returned: ``projects/{project_id}`` or + ``projects/{project_id}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferConfigsAsyncPager: + The returned list of pipelines in the + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.ListTransferConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_transfer_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTransferConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def schedule_transfer_runs(self, + request: datatransfer.ScheduleTransferRunsRequest = None, + *, + parent: str = None, + start_time: timestamp_pb2.Timestamp = None, + end_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.ScheduleTransferRunsResponse: + r"""Creates transfer runs for a time range [start_time, end_time]. + For each date - or whatever granularity the data source supports + - in the range, one transfer run is created. Note that runs are + created per UTC time in the time range. DEPRECATED: use + StartManualTransferRuns instead. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsRequest`): + The request object. A request to schedule transfer runs + for a time range. + parent (:class:`str`): + Required. Transfer configuration name in the form: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. Start time of the range of transfer runs. For + example, ``"2017-05-25T00:00:00+00:00"``. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + end_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. End time of the range of transfer runs. For + example, ``"2017-05-30T00:00:00+00:00"``. + + This corresponds to the ``end_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse: + A response to schedule transfer runs + for a time range. + + """ + warnings.warn("DataTransferServiceAsyncClient.schedule_transfer_runs is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, start_time, end_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.ScheduleTransferRunsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if start_time is not None: + request.start_time = start_time + if end_time is not None: + request.end_time = end_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.schedule_transfer_runs, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def start_manual_transfer_runs(self, + request: datatransfer.StartManualTransferRunsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.StartManualTransferRunsResponse: + r"""Start manual transfer runs to be executed now with schedule_time + equal to current time. The transfer runs can be created for a + time range where the run_time is between start_time (inclusive) + and end_time (exclusive), or for a specific run_time. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest`): + The request object. A request to start manual transfer + runs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.bigquery_datatransfer_v1.types.StartManualTransferRunsResponse: + A response to start manual transfer + runs. + + """ + # Create or coerce a protobuf request object. + request = datatransfer.StartManualTransferRunsRequest(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.start_manual_transfer_runs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_transfer_run(self, + request: datatransfer.GetTransferRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferRun: + r"""Returns information about the particular transfer + run. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetTransferRunRequest`): + The request object. A request to get data transfer run + information. + name (:class:`str`): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferRun: + Represents a data transfer run. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.GetTransferRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_transfer_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_transfer_run(self, + request: datatransfer.DeleteTransferRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified transfer run. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.DeleteTransferRunRequest`): + The request object. A request to delete data transfer + run information. + name (:class:`str`): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.DeleteTransferRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_transfer_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_transfer_runs(self, + request: datatransfer.ListTransferRunsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferRunsAsyncPager: + r"""Returns information about running and completed jobs. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest`): + The request object. A request to list data transfer + runs. UI can use this method to show/filter specific + data transfer runs. The data source can use this method + to request all scheduled transfer runs. + parent (:class:`str`): + Required. Name of transfer configuration for which + transfer runs should be retrieved. Format of transfer + configuration resource name is: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferRunsAsyncPager: + The returned list of pipelines in the + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.ListTransferRunsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_transfer_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTransferRunsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_transfer_logs(self, + request: datatransfer.ListTransferLogsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferLogsAsyncPager: + r"""Returns user facing log messages for the data + transfer run. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsRequest`): + The request object. A request to get user facing log + messages associated with data transfer run. + parent (:class:`str`): + Required. Transfer run name in the form: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferLogsAsyncPager: + The returned list transfer run + messages. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.ListTransferLogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_transfer_logs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTransferLogsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def check_valid_creds(self, + request: datatransfer.CheckValidCredsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.CheckValidCredsResponse: + r"""Returns true if valid credentials exist for the given + data source and requesting user. + Some data sources doesn't support service account, so we + need to talk to them on behalf of the end user. This API + just checks whether we have OAuth token for the + particular user, which is a pre-requisite before user + can create a transfer config. + + Args: + request (:class:`google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsRequest`): + The request object. A request to determine whether the + user has valid credentials. This method is used to limit + the number of OAuth popups in the user interface. The + user id is inferred from the API call context. + If the data source has the Google+ authorization type, + this method returns false, as it cannot be determined + whether the credentials are already valid merely based + on the user id. + name (:class:`str`): + Required. The data source in the form: + ``projects/{project_id}/dataSources/{data_source_id}`` + or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsResponse: + A response indicating whether the + credentials exist and are valid. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datatransfer.CheckValidCredsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.check_valid_creds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-bigquery-datatransfer", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataTransferServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py new file mode 100644 index 00000000..c765505c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py @@ -0,0 +1,1572 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources +import warnings + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataTransferServiceGrpcTransport +from .transports.grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport + + +class DataTransferServiceClientMeta(type): + """Metaclass for the DataTransferService 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[DataTransferServiceTransport]] + _transport_registry["grpc"] = DataTransferServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataTransferServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DataTransferServiceTransport]: + """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 DataTransferServiceClient(metaclass=DataTransferServiceClientMeta): + """The Google BigQuery Data Transfer Service API enables + BigQuery users to configure the transfer of their data from + other Google Products into BigQuery. This service contains + methods that are end user exposed. It backs up the frontend. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "bigquerydatatransfer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataTransferServiceClient: 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: + DataTransferServiceClient: 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) -> DataTransferServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataTransferServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_source_path(project: str,data_source: str,) -> str: + """Returns a fully-qualified data_source string.""" + return "projects/{project}/dataSources/{data_source}".format(project=project, data_source=data_source, ) + + @staticmethod + def parse_data_source_path(path: str) -> Dict[str,str]: + """Parses a data_source path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dataSources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def run_path(project: str,transfer_config: str,run: str,) -> str: + """Returns a fully-qualified run string.""" + return "projects/{project}/transferConfigs/{transfer_config}/runs/{run}".format(project=project, transfer_config=transfer_config, run=run, ) + + @staticmethod + def parse_run_path(path: str) -> Dict[str,str]: + """Parses a run path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/transferConfigs/(?P.+?)/runs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transfer_config_path(project: str,transfer_config: str,) -> str: + """Returns a fully-qualified transfer_config string.""" + return "projects/{project}/transferConfigs/{transfer_config}".format(project=project, transfer_config=transfer_config, ) + + @staticmethod + def parse_transfer_config_path(path: str) -> Dict[str,str]: + """Parses a transfer_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/transferConfigs/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataTransferServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data 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 (Union[str, DataTransferServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DataTransferServiceTransport): + # transport is a DataTransferServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def get_data_source(self, + request: datatransfer.GetDataSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.DataSource: + r"""Retrieves a supported data source and returns its + settings, which can be used for UI rendering. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.GetDataSourceRequest): + The request object. A request to get data source info. + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/dataSources/{data_source_id}`` + or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.DataSource: + Represents data source metadata. + Metadata is sufficient to render UI and + request proper OAuth tokens. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.GetDataSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.GetDataSourceRequest): + request = datatransfer.GetDataSourceRequest(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_data_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_sources(self, + request: datatransfer.ListDataSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataSourcesPager: + r"""Lists supported data sources and returns their + settings, which can be used for UI rendering. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesRequest): + The request object. Request to list supported data + sources and their data transfer settings. + parent (str): + Required. The BigQuery project id for which data sources + should be returned. Must be in the form: + ``projects/{project_id}`` or + \`projects/{project_id}/locations/{location_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListDataSourcesPager: + Returns list of supported data + sources and their metadata. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.ListDataSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.ListDataSourcesRequest): + request = datatransfer.ListDataSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_sources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataSourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_transfer_config(self, + request: datatransfer.CreateTransferConfigRequest = None, + *, + parent: str = None, + transfer_config: transfer.TransferConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Creates a new data transfer configuration. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.CreateTransferConfigRequest): + The request object. A request to create a data transfer + configuration. If new credentials are needed for this + transfer configuration, an authorization code must be + provided. If an authorization code is provided, the + transfer configuration will be associated with the user + id corresponding to the authorization code. Otherwise, + the transfer configuration will be associated with the + calling user. + parent (str): + Required. The BigQuery project id where the transfer + configuration should be created. Must be in the format + projects/{project_id}/locations/{location_id} or + projects/{project_id}. If specified location and + location of the destination bigquery dataset do not + match - the request will fail. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): + Required. Data transfer configuration + to create. + + This corresponds to the ``transfer_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transfer_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.CreateTransferConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.CreateTransferConfigRequest): + request = datatransfer.CreateTransferConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transfer_config is not None: + request.transfer_config = transfer_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_transfer_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_transfer_config(self, + request: datatransfer.UpdateTransferConfigRequest = None, + *, + transfer_config: transfer.TransferConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Updates a data transfer configuration. + All fields must be set, even if they are not updated. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.UpdateTransferConfigRequest): + The request object. A request to update a transfer + configuration. To update the user id of the transfer + configuration, an authorization code needs to be + provided. + transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): + Required. Data transfer configuration + to create. + + This corresponds to the ``transfer_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Required list of fields to + be updated in this request. + + 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.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transfer_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.UpdateTransferConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.UpdateTransferConfigRequest): + request = datatransfer.UpdateTransferConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transfer_config is not None: + request.transfer_config = transfer_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_transfer_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transfer_config.name", request.transfer_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_transfer_config(self, + request: datatransfer.DeleteTransferConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a data transfer configuration, + including any associated transfer runs and logs. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.DeleteTransferConfigRequest): + The request object. A request to delete data transfer + information. All associated transfer runs and log + messages will be deleted as well. + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.DeleteTransferConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.DeleteTransferConfigRequest): + request = datatransfer.DeleteTransferConfigRequest(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_transfer_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_transfer_config(self, + request: datatransfer.GetTransferConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferConfig: + r"""Returns information about a data transfer config. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.GetTransferConfigRequest): + The request object. A request to get data transfer + information. + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferConfig: + Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data + transfer. For example, destination_dataset_id + specifies where data should be stored. When a new + transfer configuration is created, the specified + destination_dataset_id is created when needed and + shared with the appropriate data source service + account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.GetTransferConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.GetTransferConfigRequest): + request = datatransfer.GetTransferConfigRequest(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_transfer_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_transfer_configs(self, + request: datatransfer.ListTransferConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferConfigsPager: + r"""Returns information about all transfer configs owned + by a project in the specified location. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): + The request object. A request to list data transfers + configured for a BigQuery project. + parent (str): + Required. The BigQuery project id for which data sources + should be returned: ``projects/{project_id}`` or + ``projects/{project_id}/locations/{location_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferConfigsPager: + The returned list of pipelines in the + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.ListTransferConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.ListTransferConfigsRequest): + request = datatransfer.ListTransferConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transfer_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTransferConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def schedule_transfer_runs(self, + request: datatransfer.ScheduleTransferRunsRequest = None, + *, + parent: str = None, + start_time: timestamp_pb2.Timestamp = None, + end_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.ScheduleTransferRunsResponse: + r"""Creates transfer runs for a time range [start_time, end_time]. + For each date - or whatever granularity the data source supports + - in the range, one transfer run is created. Note that runs are + created per UTC time in the time range. DEPRECATED: use + StartManualTransferRuns instead. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsRequest): + The request object. A request to schedule transfer runs + for a time range. + parent (str): + Required. Transfer configuration name in the form: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Start time of the range of transfer runs. For + example, ``"2017-05-25T00:00:00+00:00"``. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. End time of the range of transfer runs. For + example, ``"2017-05-30T00:00:00+00:00"``. + + This corresponds to the ``end_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse: + A response to schedule transfer runs + for a time range. + + """ + warnings.warn("DataTransferServiceClient.schedule_transfer_runs is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, start_time, end_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.ScheduleTransferRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.ScheduleTransferRunsRequest): + request = datatransfer.ScheduleTransferRunsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if start_time is not None: + request.start_time = start_time + if end_time is not None: + request.end_time = end_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.schedule_transfer_runs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def start_manual_transfer_runs(self, + request: datatransfer.StartManualTransferRunsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.StartManualTransferRunsResponse: + r"""Start manual transfer runs to be executed now with schedule_time + equal to current time. The transfer runs can be created for a + time range where the run_time is between start_time (inclusive) + and end_time (exclusive), or for a specific run_time. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest): + The request object. A request to start manual transfer + runs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.bigquery_datatransfer_v1.types.StartManualTransferRunsResponse: + A response to start manual transfer + runs. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.StartManualTransferRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.StartManualTransferRunsRequest): + request = datatransfer.StartManualTransferRunsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_manual_transfer_runs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_transfer_run(self, + request: datatransfer.GetTransferRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transfer.TransferRun: + r"""Returns information about the particular transfer + run. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.GetTransferRunRequest): + The request object. A request to get data transfer run + information. + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.TransferRun: + Represents a data transfer run. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.GetTransferRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.GetTransferRunRequest): + request = datatransfer.GetTransferRunRequest(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_transfer_run] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_transfer_run(self, + request: datatransfer.DeleteTransferRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified transfer run. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.DeleteTransferRunRequest): + The request object. A request to delete data transfer + run information. + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.DeleteTransferRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.DeleteTransferRunRequest): + request = datatransfer.DeleteTransferRunRequest(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_transfer_run] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_transfer_runs(self, + request: datatransfer.ListTransferRunsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferRunsPager: + r"""Returns information about running and completed jobs. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest): + The request object. A request to list data transfer + runs. UI can use this method to show/filter specific + data transfer runs. The data source can use this method + to request all scheduled transfer runs. + parent (str): + Required. Name of transfer configuration for which + transfer runs should be retrieved. Format of transfer + configuration resource name is: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferRunsPager: + The returned list of pipelines in the + project. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.ListTransferRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.ListTransferRunsRequest): + request = datatransfer.ListTransferRunsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transfer_runs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTransferRunsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_transfer_logs(self, + request: datatransfer.ListTransferLogsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransferLogsPager: + r"""Returns user facing log messages for the data + transfer run. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsRequest): + The request object. A request to get user facing log + messages associated with data transfer run. + parent (str): + Required. Transfer run name in the form: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferLogsPager: + The returned list transfer run + messages. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.ListTransferLogsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.ListTransferLogsRequest): + request = datatransfer.ListTransferLogsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transfer_logs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTransferLogsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def check_valid_creds(self, + request: datatransfer.CheckValidCredsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datatransfer.CheckValidCredsResponse: + r"""Returns true if valid credentials exist for the given + data source and requesting user. + Some data sources doesn't support service account, so we + need to talk to them on behalf of the end user. This API + just checks whether we have OAuth token for the + particular user, which is a pre-requisite before user + can create a transfer config. + + Args: + request (google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsRequest): + The request object. A request to determine whether the + user has valid credentials. This method is used to limit + the number of OAuth popups in the user interface. The + user id is inferred from the API call context. + If the data source has the Google+ authorization type, + this method returns false, as it cannot be determined + whether the credentials are already valid merely based + on the user id. + name (str): + Required. The data source in the form: + ``projects/{project_id}/dataSources/{data_source_id}`` + or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsResponse: + A response indicating whether the + credentials exist and are valid. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datatransfer.CheckValidCredsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datatransfer.CheckValidCredsRequest): + request = datatransfer.CheckValidCredsRequest(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.check_valid_creds] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-bigquery-datatransfer", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataTransferServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py new file mode 100644 index 00000000..77d00714 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py @@ -0,0 +1,507 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer + + +class ListDataSourcesPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` + 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[..., datatransfer.ListDataSourcesResponse], + request: datatransfer.ListDataSourcesRequest, + response: datatransfer.ListDataSourcesResponse, + *, + 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.bigquery_datatransfer_v1.types.ListDataSourcesRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListDataSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[datatransfer.ListDataSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[datatransfer.DataSource]: + for page in self.pages: + yield from page.data_sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataSourcesAsyncPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` + 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[datatransfer.ListDataSourcesResponse]], + request: datatransfer.ListDataSourcesRequest, + response: datatransfer.ListDataSourcesResponse, + *, + 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.bigquery_datatransfer_v1.types.ListDataSourcesRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListDataSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[datatransfer.ListDataSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[datatransfer.DataSource]: + async def async_generator(): + async for page in self.pages: + for response in page.data_sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferConfigsPager: + """A pager for iterating through ``list_transfer_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transfer_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransferConfigs`` requests and continue to iterate + through the ``transfer_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` + 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[..., datatransfer.ListTransferConfigsResponse], + request: datatransfer.ListTransferConfigsRequest, + response: datatransfer.ListTransferConfigsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[datatransfer.ListTransferConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[transfer.TransferConfig]: + for page in self.pages: + yield from page.transfer_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferConfigsAsyncPager: + """A pager for iterating through ``list_transfer_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transfer_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransferConfigs`` requests and continue to iterate + through the ``transfer_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` + 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[datatransfer.ListTransferConfigsResponse]], + request: datatransfer.ListTransferConfigsRequest, + response: datatransfer.ListTransferConfigsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[datatransfer.ListTransferConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[transfer.TransferConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.transfer_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferRunsPager: + """A pager for iterating through ``list_transfer_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transfer_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransferRuns`` requests and continue to iterate + through the ``transfer_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` + 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[..., datatransfer.ListTransferRunsResponse], + request: datatransfer.ListTransferRunsRequest, + response: datatransfer.ListTransferRunsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferRunsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[datatransfer.ListTransferRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[transfer.TransferRun]: + for page in self.pages: + yield from page.transfer_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferRunsAsyncPager: + """A pager for iterating through ``list_transfer_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transfer_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransferRuns`` requests and continue to iterate + through the ``transfer_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` + 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[datatransfer.ListTransferRunsResponse]], + request: datatransfer.ListTransferRunsRequest, + response: datatransfer.ListTransferRunsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferRunsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[datatransfer.ListTransferRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[transfer.TransferRun]: + async def async_generator(): + async for page in self.pages: + for response in page.transfer_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferLogsPager: + """A pager for iterating through ``list_transfer_logs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transfer_messages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransferLogs`` requests and continue to iterate + through the ``transfer_messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` + 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[..., datatransfer.ListTransferLogsResponse], + request: datatransfer.ListTransferLogsRequest, + response: datatransfer.ListTransferLogsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferLogsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferLogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[datatransfer.ListTransferLogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[transfer.TransferMessage]: + for page in self.pages: + yield from page.transfer_messages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransferLogsAsyncPager: + """A pager for iterating through ``list_transfer_logs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transfer_messages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransferLogs`` requests and continue to iterate + through the ``transfer_messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` + 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[datatransfer.ListTransferLogsResponse]], + request: datatransfer.ListTransferLogsRequest, + response: datatransfer.ListTransferLogsResponse, + *, + 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.bigquery_datatransfer_v1.types.ListTransferLogsRequest): + The initial request object. + response (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = datatransfer.ListTransferLogsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[datatransfer.ListTransferLogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[transfer.TransferMessage]: + async def async_generator(): + async for page in self.pages: + for response in page.transfer_messages: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py new file mode 100644 index 00000000..0607aff0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 DataTransferServiceTransport +from .grpc import DataTransferServiceGrpcTransport +from .grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataTransferServiceTransport]] +_transport_registry['grpc'] = DataTransferServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DataTransferServiceGrpcAsyncIOTransport + +__all__ = ( + 'DataTransferServiceTransport', + 'DataTransferServiceGrpcTransport', + 'DataTransferServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py new file mode 100644 index 00000000..17fa2de7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py @@ -0,0 +1,422 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-bigquery-datatransfer', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DataTransferServiceTransport(abc.ABC): + """Abstract transport class for DataTransferService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'bigquerydatatransfer.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_data_source: gapic_v1.method.wrap_method( + self.get_data_source, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.list_data_sources: gapic_v1.method.wrap_method( + self.list_data_sources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.create_transfer_config: gapic_v1.method.wrap_method( + self.create_transfer_config, + default_timeout=30.0, + client_info=client_info, + ), + self.update_transfer_config: gapic_v1.method.wrap_method( + self.update_transfer_config, + default_timeout=30.0, + client_info=client_info, + ), + self.delete_transfer_config: gapic_v1.method.wrap_method( + self.delete_transfer_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.get_transfer_config: gapic_v1.method.wrap_method( + self.get_transfer_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.list_transfer_configs: gapic_v1.method.wrap_method( + self.list_transfer_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.schedule_transfer_runs: gapic_v1.method.wrap_method( + self.schedule_transfer_runs, + default_timeout=30.0, + client_info=client_info, + ), + self.start_manual_transfer_runs: gapic_v1.method.wrap_method( + self.start_manual_transfer_runs, + default_timeout=None, + client_info=client_info, + ), + self.get_transfer_run: gapic_v1.method.wrap_method( + self.get_transfer_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.delete_transfer_run: gapic_v1.method.wrap_method( + self.delete_transfer_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.list_transfer_runs: gapic_v1.method.wrap_method( + self.list_transfer_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.list_transfer_logs: gapic_v1.method.wrap_method( + self.list_transfer_logs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + self.check_valid_creds: gapic_v1.method.wrap_method( + self.check_valid_creds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, + client_info=client_info, + ), + } + + @property + def get_data_source(self) -> Callable[ + [datatransfer.GetDataSourceRequest], + Union[ + datatransfer.DataSource, + Awaitable[datatransfer.DataSource] + ]]: + raise NotImplementedError() + + @property + def list_data_sources(self) -> Callable[ + [datatransfer.ListDataSourcesRequest], + Union[ + datatransfer.ListDataSourcesResponse, + Awaitable[datatransfer.ListDataSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def create_transfer_config(self) -> Callable[ + [datatransfer.CreateTransferConfigRequest], + Union[ + transfer.TransferConfig, + Awaitable[transfer.TransferConfig] + ]]: + raise NotImplementedError() + + @property + def update_transfer_config(self) -> Callable[ + [datatransfer.UpdateTransferConfigRequest], + Union[ + transfer.TransferConfig, + Awaitable[transfer.TransferConfig] + ]]: + raise NotImplementedError() + + @property + def delete_transfer_config(self) -> Callable[ + [datatransfer.DeleteTransferConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_transfer_config(self) -> Callable[ + [datatransfer.GetTransferConfigRequest], + Union[ + transfer.TransferConfig, + Awaitable[transfer.TransferConfig] + ]]: + raise NotImplementedError() + + @property + def list_transfer_configs(self) -> Callable[ + [datatransfer.ListTransferConfigsRequest], + Union[ + datatransfer.ListTransferConfigsResponse, + Awaitable[datatransfer.ListTransferConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def schedule_transfer_runs(self) -> Callable[ + [datatransfer.ScheduleTransferRunsRequest], + Union[ + datatransfer.ScheduleTransferRunsResponse, + Awaitable[datatransfer.ScheduleTransferRunsResponse] + ]]: + raise NotImplementedError() + + @property + def start_manual_transfer_runs(self) -> Callable[ + [datatransfer.StartManualTransferRunsRequest], + Union[ + datatransfer.StartManualTransferRunsResponse, + Awaitable[datatransfer.StartManualTransferRunsResponse] + ]]: + raise NotImplementedError() + + @property + def get_transfer_run(self) -> Callable[ + [datatransfer.GetTransferRunRequest], + Union[ + transfer.TransferRun, + Awaitable[transfer.TransferRun] + ]]: + raise NotImplementedError() + + @property + def delete_transfer_run(self) -> Callable[ + [datatransfer.DeleteTransferRunRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_transfer_runs(self) -> Callable[ + [datatransfer.ListTransferRunsRequest], + Union[ + datatransfer.ListTransferRunsResponse, + Awaitable[datatransfer.ListTransferRunsResponse] + ]]: + raise NotImplementedError() + + @property + def list_transfer_logs(self) -> Callable[ + [datatransfer.ListTransferLogsRequest], + Union[ + datatransfer.ListTransferLogsResponse, + Awaitable[datatransfer.ListTransferLogsResponse] + ]]: + raise NotImplementedError() + + @property + def check_valid_creds(self) -> Callable[ + [datatransfer.CheckValidCredsRequest], + Union[ + datatransfer.CheckValidCredsResponse, + Awaitable[datatransfer.CheckValidCredsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DataTransferServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py new file mode 100644 index 00000000..60486c31 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py @@ -0,0 +1,615 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import empty_pb2 # type: ignore +from .base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO + + +class DataTransferServiceGrpcTransport(DataTransferServiceTransport): + """gRPC backend transport for DataTransferService. + + The Google BigQuery Data Transfer Service API enables + BigQuery users to configure the transfer of their data from + other Google Products into BigQuery. This service contains + methods that are end user exposed. It backs up the frontend. + + 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 = 'bigquerydatatransfer.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 = 'bigquerydatatransfer.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: 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 get_data_source(self) -> Callable[ + [datatransfer.GetDataSourceRequest], + datatransfer.DataSource]: + r"""Return a callable for the get data source method over gRPC. + + Retrieves a supported data source and returns its + settings, which can be used for UI rendering. + + Returns: + Callable[[~.GetDataSourceRequest], + ~.DataSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['get_data_source'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetDataSource', + request_serializer=datatransfer.GetDataSourceRequest.serialize, + response_deserializer=datatransfer.DataSource.deserialize, + ) + return self._stubs['get_data_source'] + + @property + def list_data_sources(self) -> Callable[ + [datatransfer.ListDataSourcesRequest], + datatransfer.ListDataSourcesResponse]: + r"""Return a callable for the list data sources method over gRPC. + + Lists supported data sources and returns their + settings, which can be used for UI rendering. + + Returns: + Callable[[~.ListDataSourcesRequest], + ~.ListDataSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_sources' not in self._stubs: + self._stubs['list_data_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListDataSources', + request_serializer=datatransfer.ListDataSourcesRequest.serialize, + response_deserializer=datatransfer.ListDataSourcesResponse.deserialize, + ) + return self._stubs['list_data_sources'] + + @property + def create_transfer_config(self) -> Callable[ + [datatransfer.CreateTransferConfigRequest], + transfer.TransferConfig]: + r"""Return a callable for the create transfer config method over gRPC. + + Creates a new data transfer configuration. + + Returns: + Callable[[~.CreateTransferConfigRequest], + ~.TransferConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CreateTransferConfig', + request_serializer=datatransfer.CreateTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['create_transfer_config'] + + @property + def update_transfer_config(self) -> Callable[ + [datatransfer.UpdateTransferConfigRequest], + transfer.TransferConfig]: + r"""Return a callable for the update transfer config method over gRPC. + + Updates a data transfer configuration. + All fields must be set, even if they are not updated. + + Returns: + Callable[[~.UpdateTransferConfigRequest], + ~.TransferConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/UpdateTransferConfig', + request_serializer=datatransfer.UpdateTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['update_transfer_config'] + + @property + def delete_transfer_config(self) -> Callable[ + [datatransfer.DeleteTransferConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transfer config method over gRPC. + + Deletes a data transfer configuration, + including any associated transfer runs and logs. + + Returns: + Callable[[~.DeleteTransferConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferConfig', + request_serializer=datatransfer.DeleteTransferConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_config'] + + @property + def get_transfer_config(self) -> Callable[ + [datatransfer.GetTransferConfigRequest], + transfer.TransferConfig]: + r"""Return a callable for the get transfer config method over gRPC. + + Returns information about a data transfer config. + + Returns: + Callable[[~.GetTransferConfigRequest], + ~.TransferConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['get_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferConfig', + request_serializer=datatransfer.GetTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['get_transfer_config'] + + @property + def list_transfer_configs(self) -> Callable[ + [datatransfer.ListTransferConfigsRequest], + datatransfer.ListTransferConfigsResponse]: + r"""Return a callable for the list transfer configs method over gRPC. + + Returns information about all transfer configs owned + by a project in the specified location. + + Returns: + Callable[[~.ListTransferConfigsRequest], + ~.ListTransferConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_configs' not in self._stubs: + self._stubs['list_transfer_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferConfigs', + request_serializer=datatransfer.ListTransferConfigsRequest.serialize, + response_deserializer=datatransfer.ListTransferConfigsResponse.deserialize, + ) + return self._stubs['list_transfer_configs'] + + @property + def schedule_transfer_runs(self) -> Callable[ + [datatransfer.ScheduleTransferRunsRequest], + datatransfer.ScheduleTransferRunsResponse]: + r"""Return a callable for the schedule transfer runs method over gRPC. + + Creates transfer runs for a time range [start_time, end_time]. + For each date - or whatever granularity the data source supports + - in the range, one transfer run is created. Note that runs are + created per UTC time in the time range. DEPRECATED: use + StartManualTransferRuns instead. + + Returns: + Callable[[~.ScheduleTransferRunsRequest], + ~.ScheduleTransferRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'schedule_transfer_runs' not in self._stubs: + self._stubs['schedule_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ScheduleTransferRuns', + request_serializer=datatransfer.ScheduleTransferRunsRequest.serialize, + response_deserializer=datatransfer.ScheduleTransferRunsResponse.deserialize, + ) + return self._stubs['schedule_transfer_runs'] + + @property + def start_manual_transfer_runs(self) -> Callable[ + [datatransfer.StartManualTransferRunsRequest], + datatransfer.StartManualTransferRunsResponse]: + r"""Return a callable for the start manual transfer runs method over gRPC. + + Start manual transfer runs to be executed now with schedule_time + equal to current time. The transfer runs can be created for a + time range where the run_time is between start_time (inclusive) + and end_time (exclusive), or for a specific run_time. + + Returns: + Callable[[~.StartManualTransferRunsRequest], + ~.StartManualTransferRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_manual_transfer_runs' not in self._stubs: + self._stubs['start_manual_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/StartManualTransferRuns', + request_serializer=datatransfer.StartManualTransferRunsRequest.serialize, + response_deserializer=datatransfer.StartManualTransferRunsResponse.deserialize, + ) + return self._stubs['start_manual_transfer_runs'] + + @property + def get_transfer_run(self) -> Callable[ + [datatransfer.GetTransferRunRequest], + transfer.TransferRun]: + r"""Return a callable for the get transfer run method over gRPC. + + Returns information about the particular transfer + run. + + Returns: + Callable[[~.GetTransferRunRequest], + ~.TransferRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_run' not in self._stubs: + self._stubs['get_transfer_run'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferRun', + request_serializer=datatransfer.GetTransferRunRequest.serialize, + response_deserializer=transfer.TransferRun.deserialize, + ) + return self._stubs['get_transfer_run'] + + @property + def delete_transfer_run(self) -> Callable[ + [datatransfer.DeleteTransferRunRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transfer run method over gRPC. + + Deletes the specified transfer run. + + Returns: + Callable[[~.DeleteTransferRunRequest], + ~.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_run' not in self._stubs: + self._stubs['delete_transfer_run'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferRun', + request_serializer=datatransfer.DeleteTransferRunRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_run'] + + @property + def list_transfer_runs(self) -> Callable[ + [datatransfer.ListTransferRunsRequest], + datatransfer.ListTransferRunsResponse]: + r"""Return a callable for the list transfer runs method over gRPC. + + Returns information about running and completed jobs. + + Returns: + Callable[[~.ListTransferRunsRequest], + ~.ListTransferRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_runs' not in self._stubs: + self._stubs['list_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferRuns', + request_serializer=datatransfer.ListTransferRunsRequest.serialize, + response_deserializer=datatransfer.ListTransferRunsResponse.deserialize, + ) + return self._stubs['list_transfer_runs'] + + @property + def list_transfer_logs(self) -> Callable[ + [datatransfer.ListTransferLogsRequest], + datatransfer.ListTransferLogsResponse]: + r"""Return a callable for the list transfer logs method over gRPC. + + Returns user facing log messages for the data + transfer run. + + Returns: + Callable[[~.ListTransferLogsRequest], + ~.ListTransferLogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_logs' not in self._stubs: + self._stubs['list_transfer_logs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferLogs', + request_serializer=datatransfer.ListTransferLogsRequest.serialize, + response_deserializer=datatransfer.ListTransferLogsResponse.deserialize, + ) + return self._stubs['list_transfer_logs'] + + @property + def check_valid_creds(self) -> Callable[ + [datatransfer.CheckValidCredsRequest], + datatransfer.CheckValidCredsResponse]: + r"""Return a callable for the check valid creds method over gRPC. + + Returns true if valid credentials exist for the given + data source and requesting user. + Some data sources doesn't support service account, so we + need to talk to them on behalf of the end user. This API + just checks whether we have OAuth token for the + particular user, which is a pre-requisite before user + can create a transfer config. + + Returns: + Callable[[~.CheckValidCredsRequest], + ~.CheckValidCredsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'check_valid_creds' not in self._stubs: + self._stubs['check_valid_creds'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CheckValidCreds', + request_serializer=datatransfer.CheckValidCredsRequest.serialize, + response_deserializer=datatransfer.CheckValidCredsResponse.deserialize, + ) + return self._stubs['check_valid_creds'] + + +__all__ = ( + 'DataTransferServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..74b122ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py @@ -0,0 +1,619 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import empty_pb2 # type: ignore +from .base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DataTransferServiceGrpcTransport + + +class DataTransferServiceGrpcAsyncIOTransport(DataTransferServiceTransport): + """gRPC AsyncIO backend transport for DataTransferService. + + The Google BigQuery Data Transfer Service API enables + BigQuery users to configure the transfer of their data from + other Google Products into BigQuery. This service contains + methods that are end user exposed. It backs up the frontend. + + 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 = 'bigquerydatatransfer.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'bigquerydatatransfer.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin 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 grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 get_data_source(self) -> Callable[ + [datatransfer.GetDataSourceRequest], + Awaitable[datatransfer.DataSource]]: + r"""Return a callable for the get data source method over gRPC. + + Retrieves a supported data source and returns its + settings, which can be used for UI rendering. + + Returns: + Callable[[~.GetDataSourceRequest], + Awaitable[~.DataSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_source' not in self._stubs: + self._stubs['get_data_source'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetDataSource', + request_serializer=datatransfer.GetDataSourceRequest.serialize, + response_deserializer=datatransfer.DataSource.deserialize, + ) + return self._stubs['get_data_source'] + + @property + def list_data_sources(self) -> Callable[ + [datatransfer.ListDataSourcesRequest], + Awaitable[datatransfer.ListDataSourcesResponse]]: + r"""Return a callable for the list data sources method over gRPC. + + Lists supported data sources and returns their + settings, which can be used for UI rendering. + + Returns: + Callable[[~.ListDataSourcesRequest], + Awaitable[~.ListDataSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_sources' not in self._stubs: + self._stubs['list_data_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListDataSources', + request_serializer=datatransfer.ListDataSourcesRequest.serialize, + response_deserializer=datatransfer.ListDataSourcesResponse.deserialize, + ) + return self._stubs['list_data_sources'] + + @property + def create_transfer_config(self) -> Callable[ + [datatransfer.CreateTransferConfigRequest], + Awaitable[transfer.TransferConfig]]: + r"""Return a callable for the create transfer config method over gRPC. + + Creates a new data transfer configuration. + + Returns: + Callable[[~.CreateTransferConfigRequest], + Awaitable[~.TransferConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CreateTransferConfig', + request_serializer=datatransfer.CreateTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['create_transfer_config'] + + @property + def update_transfer_config(self) -> Callable[ + [datatransfer.UpdateTransferConfigRequest], + Awaitable[transfer.TransferConfig]]: + r"""Return a callable for the update transfer config method over gRPC. + + Updates a data transfer configuration. + All fields must be set, even if they are not updated. + + Returns: + Callable[[~.UpdateTransferConfigRequest], + Awaitable[~.TransferConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/UpdateTransferConfig', + request_serializer=datatransfer.UpdateTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['update_transfer_config'] + + @property + def delete_transfer_config(self) -> Callable[ + [datatransfer.DeleteTransferConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transfer config method over gRPC. + + Deletes a data transfer configuration, + including any associated transfer runs and logs. + + Returns: + Callable[[~.DeleteTransferConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferConfig', + request_serializer=datatransfer.DeleteTransferConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_config'] + + @property + def get_transfer_config(self) -> Callable[ + [datatransfer.GetTransferConfigRequest], + Awaitable[transfer.TransferConfig]]: + r"""Return a callable for the get transfer config method over gRPC. + + Returns information about a data transfer config. + + Returns: + Callable[[~.GetTransferConfigRequest], + Awaitable[~.TransferConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['get_transfer_config'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferConfig', + request_serializer=datatransfer.GetTransferConfigRequest.serialize, + response_deserializer=transfer.TransferConfig.deserialize, + ) + return self._stubs['get_transfer_config'] + + @property + def list_transfer_configs(self) -> Callable[ + [datatransfer.ListTransferConfigsRequest], + Awaitable[datatransfer.ListTransferConfigsResponse]]: + r"""Return a callable for the list transfer configs method over gRPC. + + Returns information about all transfer configs owned + by a project in the specified location. + + Returns: + Callable[[~.ListTransferConfigsRequest], + Awaitable[~.ListTransferConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_configs' not in self._stubs: + self._stubs['list_transfer_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferConfigs', + request_serializer=datatransfer.ListTransferConfigsRequest.serialize, + response_deserializer=datatransfer.ListTransferConfigsResponse.deserialize, + ) + return self._stubs['list_transfer_configs'] + + @property + def schedule_transfer_runs(self) -> Callable[ + [datatransfer.ScheduleTransferRunsRequest], + Awaitable[datatransfer.ScheduleTransferRunsResponse]]: + r"""Return a callable for the schedule transfer runs method over gRPC. + + Creates transfer runs for a time range [start_time, end_time]. + For each date - or whatever granularity the data source supports + - in the range, one transfer run is created. Note that runs are + created per UTC time in the time range. DEPRECATED: use + StartManualTransferRuns instead. + + Returns: + Callable[[~.ScheduleTransferRunsRequest], + Awaitable[~.ScheduleTransferRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'schedule_transfer_runs' not in self._stubs: + self._stubs['schedule_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ScheduleTransferRuns', + request_serializer=datatransfer.ScheduleTransferRunsRequest.serialize, + response_deserializer=datatransfer.ScheduleTransferRunsResponse.deserialize, + ) + return self._stubs['schedule_transfer_runs'] + + @property + def start_manual_transfer_runs(self) -> Callable[ + [datatransfer.StartManualTransferRunsRequest], + Awaitable[datatransfer.StartManualTransferRunsResponse]]: + r"""Return a callable for the start manual transfer runs method over gRPC. + + Start manual transfer runs to be executed now with schedule_time + equal to current time. The transfer runs can be created for a + time range where the run_time is between start_time (inclusive) + and end_time (exclusive), or for a specific run_time. + + Returns: + Callable[[~.StartManualTransferRunsRequest], + Awaitable[~.StartManualTransferRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_manual_transfer_runs' not in self._stubs: + self._stubs['start_manual_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/StartManualTransferRuns', + request_serializer=datatransfer.StartManualTransferRunsRequest.serialize, + response_deserializer=datatransfer.StartManualTransferRunsResponse.deserialize, + ) + return self._stubs['start_manual_transfer_runs'] + + @property + def get_transfer_run(self) -> Callable[ + [datatransfer.GetTransferRunRequest], + Awaitable[transfer.TransferRun]]: + r"""Return a callable for the get transfer run method over gRPC. + + Returns information about the particular transfer + run. + + Returns: + Callable[[~.GetTransferRunRequest], + Awaitable[~.TransferRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_run' not in self._stubs: + self._stubs['get_transfer_run'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferRun', + request_serializer=datatransfer.GetTransferRunRequest.serialize, + response_deserializer=transfer.TransferRun.deserialize, + ) + return self._stubs['get_transfer_run'] + + @property + def delete_transfer_run(self) -> Callable[ + [datatransfer.DeleteTransferRunRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transfer run method over gRPC. + + Deletes the specified transfer run. + + Returns: + Callable[[~.DeleteTransferRunRequest], + 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_run' not in self._stubs: + self._stubs['delete_transfer_run'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferRun', + request_serializer=datatransfer.DeleteTransferRunRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transfer_run'] + + @property + def list_transfer_runs(self) -> Callable[ + [datatransfer.ListTransferRunsRequest], + Awaitable[datatransfer.ListTransferRunsResponse]]: + r"""Return a callable for the list transfer runs method over gRPC. + + Returns information about running and completed jobs. + + Returns: + Callable[[~.ListTransferRunsRequest], + Awaitable[~.ListTransferRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_runs' not in self._stubs: + self._stubs['list_transfer_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferRuns', + request_serializer=datatransfer.ListTransferRunsRequest.serialize, + response_deserializer=datatransfer.ListTransferRunsResponse.deserialize, + ) + return self._stubs['list_transfer_runs'] + + @property + def list_transfer_logs(self) -> Callable[ + [datatransfer.ListTransferLogsRequest], + Awaitable[datatransfer.ListTransferLogsResponse]]: + r"""Return a callable for the list transfer logs method over gRPC. + + Returns user facing log messages for the data + transfer run. + + Returns: + Callable[[~.ListTransferLogsRequest], + Awaitable[~.ListTransferLogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_logs' not in self._stubs: + self._stubs['list_transfer_logs'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferLogs', + request_serializer=datatransfer.ListTransferLogsRequest.serialize, + response_deserializer=datatransfer.ListTransferLogsResponse.deserialize, + ) + return self._stubs['list_transfer_logs'] + + @property + def check_valid_creds(self) -> Callable[ + [datatransfer.CheckValidCredsRequest], + Awaitable[datatransfer.CheckValidCredsResponse]]: + r"""Return a callable for the check valid creds method over gRPC. + + Returns true if valid credentials exist for the given + data source and requesting user. + Some data sources doesn't support service account, so we + need to talk to them on behalf of the end user. This API + just checks whether we have OAuth token for the + particular user, which is a pre-requisite before user + can create a transfer config. + + Returns: + Callable[[~.CheckValidCredsRequest], + Awaitable[~.CheckValidCredsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'check_valid_creds' not in self._stubs: + self._stubs['check_valid_creds'] = self.grpc_channel.unary_unary( + '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CheckValidCreds', + request_serializer=datatransfer.CheckValidCredsRequest.serialize, + response_deserializer=datatransfer.CheckValidCredsResponse.deserialize, + ) + return self._stubs['check_valid_creds'] + + +__all__ = ( + 'DataTransferServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py new file mode 100644 index 00000000..2e87af4c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py @@ -0,0 +1,82 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .datatransfer import ( + CheckValidCredsRequest, + CheckValidCredsResponse, + CreateTransferConfigRequest, + DataSource, + DataSourceParameter, + DeleteTransferConfigRequest, + DeleteTransferRunRequest, + GetDataSourceRequest, + GetTransferConfigRequest, + GetTransferRunRequest, + ListDataSourcesRequest, + ListDataSourcesResponse, + ListTransferConfigsRequest, + ListTransferConfigsResponse, + ListTransferLogsRequest, + ListTransferLogsResponse, + ListTransferRunsRequest, + ListTransferRunsResponse, + ScheduleTransferRunsRequest, + ScheduleTransferRunsResponse, + StartManualTransferRunsRequest, + StartManualTransferRunsResponse, + UpdateTransferConfigRequest, +) +from .transfer import ( + EmailPreferences, + ScheduleOptions, + TransferConfig, + TransferMessage, + TransferRun, + TransferState, + TransferType, +) + +__all__ = ( + 'CheckValidCredsRequest', + 'CheckValidCredsResponse', + 'CreateTransferConfigRequest', + 'DataSource', + 'DataSourceParameter', + 'DeleteTransferConfigRequest', + 'DeleteTransferRunRequest', + 'GetDataSourceRequest', + 'GetTransferConfigRequest', + 'GetTransferRunRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'ListTransferConfigsRequest', + 'ListTransferConfigsResponse', + 'ListTransferLogsRequest', + 'ListTransferLogsResponse', + 'ListTransferRunsRequest', + 'ListTransferRunsResponse', + 'ScheduleTransferRunsRequest', + 'ScheduleTransferRunsResponse', + 'StartManualTransferRunsRequest', + 'StartManualTransferRunsResponse', + 'UpdateTransferConfigRequest', + 'EmailPreferences', + 'ScheduleOptions', + 'TransferConfig', + 'TransferMessage', + 'TransferRun', + 'TransferState', + 'TransferType', +) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py new file mode 100644 index 00000000..88203842 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py @@ -0,0 +1,1023 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.bigquery.datatransfer.v1', + manifest={ + 'DataSourceParameter', + 'DataSource', + 'GetDataSourceRequest', + 'ListDataSourcesRequest', + 'ListDataSourcesResponse', + 'CreateTransferConfigRequest', + 'UpdateTransferConfigRequest', + 'GetTransferConfigRequest', + 'DeleteTransferConfigRequest', + 'GetTransferRunRequest', + 'DeleteTransferRunRequest', + 'ListTransferConfigsRequest', + 'ListTransferConfigsResponse', + 'ListTransferRunsRequest', + 'ListTransferRunsResponse', + 'ListTransferLogsRequest', + 'ListTransferLogsResponse', + 'CheckValidCredsRequest', + 'CheckValidCredsResponse', + 'ScheduleTransferRunsRequest', + 'ScheduleTransferRunsResponse', + 'StartManualTransferRunsRequest', + 'StartManualTransferRunsResponse', + }, +) + + +class DataSourceParameter(proto.Message): + r"""Represents a data source parameter with validation rules, so + that parameters can be rendered in the UI. These parameters are + given to us by supported data sources, and include all needed + information for rendering and validation. + Thus, whoever uses this api can decide to generate either + generic ui, or custom data source specific forms. + + Attributes: + param_id (str): + Parameter identifier. + display_name (str): + Parameter display name in the user interface. + description (str): + Parameter description. + type_ (google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter.Type): + Parameter type. + required (bool): + Is parameter required. + repeated (bool): + Deprecated. This field has no effect. + validation_regex (str): + Regular expression which can be used for + parameter validation. + allowed_values (Sequence[str]): + All possible values for the parameter. + min_value (google.protobuf.wrappers_pb2.DoubleValue): + For integer and double values specifies + minimum allowed value. + max_value (google.protobuf.wrappers_pb2.DoubleValue): + For integer and double values specifies + maxminum allowed value. + fields (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter]): + Deprecated. This field has no effect. + validation_description (str): + Description of the requirements for this + field, in case the user input does not fulfill + the regex pattern or min/max values. + validation_help_url (str): + URL to a help document to further explain the + naming requirements. + immutable (bool): + Cannot be changed after initial creation. + recurse (bool): + Deprecated. This field has no effect. + deprecated (bool): + If true, it should not be used in new + transfers, and it should not be visible to + users. + """ + class Type(proto.Enum): + r"""Parameter type.""" + TYPE_UNSPECIFIED = 0 + STRING = 1 + INTEGER = 2 + DOUBLE = 3 + BOOLEAN = 4 + RECORD = 5 + PLUS_PAGE = 6 + + param_id = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + type_ = proto.Field( + proto.ENUM, + number=4, + enum=Type, + ) + required = proto.Field( + proto.BOOL, + number=5, + ) + repeated = proto.Field( + proto.BOOL, + number=6, + ) + validation_regex = proto.Field( + proto.STRING, + number=7, + ) + allowed_values = proto.RepeatedField( + proto.STRING, + number=8, + ) + min_value = proto.Field( + proto.MESSAGE, + number=9, + message=wrappers_pb2.DoubleValue, + ) + max_value = proto.Field( + proto.MESSAGE, + number=10, + message=wrappers_pb2.DoubleValue, + ) + fields = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='DataSourceParameter', + ) + validation_description = proto.Field( + proto.STRING, + number=12, + ) + validation_help_url = proto.Field( + proto.STRING, + number=13, + ) + immutable = proto.Field( + proto.BOOL, + number=14, + ) + recurse = proto.Field( + proto.BOOL, + number=15, + ) + deprecated = proto.Field( + proto.BOOL, + number=20, + ) + + +class DataSource(proto.Message): + r"""Represents data source metadata. Metadata is sufficient to + render UI and request proper OAuth tokens. + + Attributes: + name (str): + Output only. Data source resource name. + data_source_id (str): + Data source id. + display_name (str): + User friendly data source name. + description (str): + User friendly data source description string. + client_id (str): + Data source client id which should be used to + receive refresh token. + scopes (Sequence[str]): + Api auth scopes for which refresh token needs + to be obtained. These are scopes needed by a + data source to prepare data and ingest them into + BigQuery, e.g., + https://www.googleapis.com/auth/bigquery + transfer_type (google.cloud.bigquery_datatransfer_v1.types.TransferType): + Deprecated. This field has no effect. + supports_multiple_transfers (bool): + Deprecated. This field has no effect. + update_deadline_seconds (int): + The number of seconds to wait for an update + from the data source before the Data Transfer + Service marks the transfer as FAILED. + default_schedule (str): + Default data transfer schedule. Examples of valid schedules + include: ``1st,3rd monday of month 15:30``, + ``every wed,fri of jan,jun 13:15``, and + ``first sunday of quarter 00:00``. + supports_custom_schedule (bool): + Specifies whether the data source supports a user defined + schedule, or operates on the default schedule. When set to + ``true``, user can override default schedule. + parameters (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter]): + Data source parameters. + help_url (str): + Url for the help document for this data + source. + authorization_type (google.cloud.bigquery_datatransfer_v1.types.DataSource.AuthorizationType): + Indicates the type of authorization. + data_refresh_type (google.cloud.bigquery_datatransfer_v1.types.DataSource.DataRefreshType): + Specifies whether the data source supports + automatic data refresh for the past few days, + and how it's supported. For some data sources, + data might not be complete until a few days + later, so it's useful to refresh data + automatically. + default_data_refresh_window_days (int): + Default data refresh window on days. Only meaningful when + ``data_refresh_type`` = ``SLIDING_WINDOW``. + manual_runs_disabled (bool): + Disables backfilling and manual run + scheduling for the data source. + minimum_schedule_interval (google.protobuf.duration_pb2.Duration): + The minimum interval for scheduler to + schedule runs. + """ + class AuthorizationType(proto.Enum): + r"""The type of authorization needed for this data source.""" + AUTHORIZATION_TYPE_UNSPECIFIED = 0 + AUTHORIZATION_CODE = 1 + GOOGLE_PLUS_AUTHORIZATION_CODE = 2 + FIRST_PARTY_OAUTH = 3 + + class DataRefreshType(proto.Enum): + r"""Represents how the data source supports data auto refresh.""" + DATA_REFRESH_TYPE_UNSPECIFIED = 0 + SLIDING_WINDOW = 1 + CUSTOM_SLIDING_WINDOW = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + data_source_id = proto.Field( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + client_id = proto.Field( + proto.STRING, + number=5, + ) + scopes = proto.RepeatedField( + proto.STRING, + number=6, + ) + transfer_type = proto.Field( + proto.ENUM, + number=7, + enum=transfer.TransferType, + ) + supports_multiple_transfers = proto.Field( + proto.BOOL, + number=8, + ) + update_deadline_seconds = proto.Field( + proto.INT32, + number=9, + ) + default_schedule = proto.Field( + proto.STRING, + number=10, + ) + supports_custom_schedule = proto.Field( + proto.BOOL, + number=11, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='DataSourceParameter', + ) + help_url = proto.Field( + proto.STRING, + number=13, + ) + authorization_type = proto.Field( + proto.ENUM, + number=14, + enum=AuthorizationType, + ) + data_refresh_type = proto.Field( + proto.ENUM, + number=15, + enum=DataRefreshType, + ) + default_data_refresh_window_days = proto.Field( + proto.INT32, + number=16, + ) + manual_runs_disabled = proto.Field( + proto.BOOL, + number=17, + ) + minimum_schedule_interval = proto.Field( + proto.MESSAGE, + number=18, + message=duration_pb2.Duration, + ) + + +class GetDataSourceRequest(proto.Message): + r"""A request to get data source info. + Attributes: + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/dataSources/{data_source_id}`` or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataSourcesRequest(proto.Message): + r"""Request to list supported data sources and their data + transfer settings. + + Attributes: + parent (str): + Required. The BigQuery project id for which data sources + should be returned. Must be in the form: + ``projects/{project_id}`` or + \`projects/{project_id}/locations/{location_id} + page_token (str): + Pagination token, which can be used to request a specific + page of ``ListDataSourcesRequest`` list results. For + multiple-page results, ``ListDataSourcesResponse`` outputs a + ``next_page`` token, which can be used as the ``page_token`` + value to request the next page of list results. + page_size (int): + Page size. The default page size is the + maximum value of 1000 results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListDataSourcesResponse(proto.Message): + r"""Returns list of supported data sources and their metadata. + Attributes: + data_sources (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSource]): + List of supported data sources and their + transfer settings. + next_page_token (str): + Output only. The next-pagination token. For multiple-page + list results, this token can be used as the + ``ListDataSourcesRequest.page_token`` to request the next + page of list results. + """ + + @property + def raw_page(self): + return self + + data_sources = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DataSource', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateTransferConfigRequest(proto.Message): + r"""A request to create a data transfer configuration. If new + credentials are needed for this transfer configuration, an + authorization code must be provided. If an authorization code is + provided, the transfer configuration will be associated with the + user id corresponding to the authorization code. Otherwise, the + transfer configuration will be associated with the calling user. + + Attributes: + parent (str): + Required. The BigQuery project id where the transfer + configuration should be created. Must be in the format + projects/{project_id}/locations/{location_id} or + projects/{project_id}. If specified location and location of + the destination bigquery dataset do not match - the request + will fail. + transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): + Required. Data transfer configuration to + create. + authorization_code (str): + Optional OAuth2 authorization code to use with this transfer + configuration. This is required if new credentials are + needed, as indicated by ``CheckValidCreds``. In order to + obtain authorization_code, please make a request to + https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=&scope=&redirect_uri= + + - client_id should be OAuth client_id of BigQuery DTS API + for the given data source returned by ListDataSources + method. + - data_source_scopes are the scopes returned by + ListDataSources method. + - redirect_uri is an optional parameter. If not specified, + then authorization code is posted to the opener of + authorization flow window. Otherwise it will be sent to + the redirect uri. A special value of + urn:ietf:wg:oauth:2.0:oob means that authorization code + should be returned in the title bar of the browser, with + the page text prompting the user to copy the code and + paste it in the application. + version_info (str): + Optional version info. If users want to find a very recent + access token, that is, immediately after approving access, + users have to set the version_info claim in the token + request. To obtain the version_info, users must use the + "none+gsession" response type. which be return a + version_info back in the authorization response which be be + put in a JWT claim in the token request. + service_account_name (str): + Optional service account name. If this field + is set, transfer config will be created with + this service account credentials. It requires + that requesting user calling this API has + permissions to act as this service account. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + transfer_config = proto.Field( + proto.MESSAGE, + number=2, + message=transfer.TransferConfig, + ) + authorization_code = proto.Field( + proto.STRING, + number=3, + ) + version_info = proto.Field( + proto.STRING, + number=5, + ) + service_account_name = proto.Field( + proto.STRING, + number=6, + ) + + +class UpdateTransferConfigRequest(proto.Message): + r"""A request to update a transfer configuration. To update the + user id of the transfer configuration, an authorization code + needs to be provided. + + Attributes: + transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): + Required. Data transfer configuration to + create. + authorization_code (str): + Optional OAuth2 authorization code to use with this transfer + configuration. If it is provided, the transfer configuration + will be associated with the authorizing user. In order to + obtain authorization_code, please make a request to + https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=&scope=&redirect_uri= + + - client_id should be OAuth client_id of BigQuery DTS API + for the given data source returned by ListDataSources + method. + - data_source_scopes are the scopes returned by + ListDataSources method. + - redirect_uri is an optional parameter. If not specified, + then authorization code is posted to the opener of + authorization flow window. Otherwise it will be sent to + the redirect uri. A special value of + urn:ietf:wg:oauth:2.0:oob means that authorization code + should be returned in the title bar of the browser, with + the page text prompting the user to copy the code and + paste it in the application. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Required list of fields to be + updated in this request. + version_info (str): + Optional version info. If users want to find a very recent + access token, that is, immediately after approving access, + users have to set the version_info claim in the token + request. To obtain the version_info, users must use the + "none+gsession" response type. which be return a + version_info back in the authorization response which be be + put in a JWT claim in the token request. + service_account_name (str): + Optional service account name. If this field is set and + "service_account_name" is set in update_mask, transfer + config will be updated to use this service account + credentials. It requires that requesting user calling this + API has permissions to act as this service account. + """ + + transfer_config = proto.Field( + proto.MESSAGE, + number=1, + message=transfer.TransferConfig, + ) + authorization_code = proto.Field( + proto.STRING, + number=3, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + version_info = proto.Field( + proto.STRING, + number=5, + ) + service_account_name = proto.Field( + proto.STRING, + number=6, + ) + + +class GetTransferConfigRequest(proto.Message): + r"""A request to get data transfer information. + Attributes: + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteTransferConfigRequest(proto.Message): + r"""A request to delete data transfer information. All associated + transfer runs and log messages will be deleted as well. + + Attributes: + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetTransferRunRequest(proto.Message): + r"""A request to get data transfer run information. + Attributes: + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteTransferRunRequest(proto.Message): + r"""A request to delete data transfer run information. + Attributes: + name (str): + Required. The field will contain name of the resource + requested, for example: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListTransferConfigsRequest(proto.Message): + r"""A request to list data transfers configured for a BigQuery + project. + + Attributes: + parent (str): + Required. The BigQuery project id for which data sources + should be returned: ``projects/{project_id}`` or + ``projects/{project_id}/locations/{location_id}`` + data_source_ids (Sequence[str]): + When specified, only configurations of + requested data sources are returned. + page_token (str): + Pagination token, which can be used to request a specific + page of ``ListTransfersRequest`` list results. For + multiple-page results, ``ListTransfersResponse`` outputs a + ``next_page`` token, which can be used as the ``page_token`` + value to request the next page of list results. + page_size (int): + Page size. The default page size is the + maximum value of 1000 results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + data_source_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListTransferConfigsResponse(proto.Message): + r"""The returned list of pipelines in the project. + Attributes: + transfer_configs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): + Output only. The stored pipeline transfer + configurations. + next_page_token (str): + Output only. The next-pagination token. For multiple-page + list results, this token can be used as the + ``ListTransferConfigsRequest.page_token`` to request the + next page of list results. + """ + + @property + def raw_page(self): + return self + + transfer_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer.TransferConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListTransferRunsRequest(proto.Message): + r"""A request to list data transfer runs. UI can use this method + to show/filter specific data transfer runs. The data source can + use this method to request all scheduled transfer runs. + + Attributes: + parent (str): + Required. Name of transfer configuration for which transfer + runs should be retrieved. Format of transfer configuration + resource name is: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + states (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferState]): + When specified, only transfer runs with + requested states are returned. + page_token (str): + Pagination token, which can be used to request a specific + page of ``ListTransferRunsRequest`` list results. For + multiple-page results, ``ListTransferRunsResponse`` outputs + a ``next_page`` token, which can be used as the + ``page_token`` value to request the next page of list + results. + page_size (int): + Page size. The default page size is the + maximum value of 1000 results. + run_attempt (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest.RunAttempt): + Indicates how run attempts are to be pulled. + """ + class RunAttempt(proto.Enum): + r"""Represents which runs should be pulled.""" + RUN_ATTEMPT_UNSPECIFIED = 0 + LATEST = 1 + + parent = proto.Field( + proto.STRING, + number=1, + ) + states = proto.RepeatedField( + proto.ENUM, + number=2, + enum=transfer.TransferState, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + run_attempt = proto.Field( + proto.ENUM, + number=5, + enum=RunAttempt, + ) + + +class ListTransferRunsResponse(proto.Message): + r"""The returned list of pipelines in the project. + Attributes: + transfer_runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): + Output only. The stored pipeline transfer + runs. + next_page_token (str): + Output only. The next-pagination token. For multiple-page + list results, this token can be used as the + ``ListTransferRunsRequest.page_token`` to request the next + page of list results. + """ + + @property + def raw_page(self): + return self + + transfer_runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer.TransferRun, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListTransferLogsRequest(proto.Message): + r"""A request to get user facing log messages associated with + data transfer run. + + Attributes: + parent (str): + Required. Transfer run name in the form: + ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` + or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` + page_token (str): + Pagination token, which can be used to request a specific + page of ``ListTransferLogsRequest`` list results. For + multiple-page results, ``ListTransferLogsResponse`` outputs + a ``next_page`` token, which can be used as the + ``page_token`` value to request the next page of list + results. + page_size (int): + Page size. The default page size is the + maximum value of 1000 results. + message_types (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferMessage.MessageSeverity]): + Message types to return. If not populated - + INFO, WARNING and ERROR messages are returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + page_size = proto.Field( + proto.INT32, + number=5, + ) + message_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=transfer.TransferMessage.MessageSeverity, + ) + + +class ListTransferLogsResponse(proto.Message): + r"""The returned list transfer run messages. + Attributes: + transfer_messages (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferMessage]): + Output only. The stored pipeline transfer + messages. + next_page_token (str): + Output only. The next-pagination token. For multiple-page + list results, this token can be used as the + ``GetTransferRunLogRequest.page_token`` to request the next + page of list results. + """ + + @property + def raw_page(self): + return self + + transfer_messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer.TransferMessage, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CheckValidCredsRequest(proto.Message): + r"""A request to determine whether the user has valid + credentials. This method is used to limit the number of OAuth + popups in the user interface. The user id is inferred from the + API call context. + If the data source has the Google+ authorization type, this + method returns false, as it cannot be determined whether the + credentials are already valid merely based on the user id. + + Attributes: + name (str): + Required. The data source in the form: + ``projects/{project_id}/dataSources/{data_source_id}`` or + ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CheckValidCredsResponse(proto.Message): + r"""A response indicating whether the credentials exist and are + valid. + + Attributes: + has_valid_creds (bool): + If set to ``true``, the credentials exist and are valid. + """ + + has_valid_creds = proto.Field( + proto.BOOL, + number=1, + ) + + +class ScheduleTransferRunsRequest(proto.Message): + r"""A request to schedule transfer runs for a time range. + Attributes: + parent (str): + Required. Transfer configuration name in the form: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Start time of the range of transfer runs. For + example, ``"2017-05-25T00:00:00+00:00"``. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. End time of the range of transfer runs. For + example, ``"2017-05-30T00:00:00+00:00"``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + start_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ScheduleTransferRunsResponse(proto.Message): + r"""A response to schedule transfer runs for a time range. + Attributes: + runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): + The transfer runs that were scheduled. + """ + + runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer.TransferRun, + ) + + +class StartManualTransferRunsRequest(proto.Message): + r"""A request to start manual transfer runs. + Attributes: + parent (str): + Transfer configuration name in the form: + ``projects/{project_id}/transferConfigs/{config_id}`` or + ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. + requested_time_range (google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest.TimeRange): + Time range for the transfer runs that should + be started. + requested_run_time (google.protobuf.timestamp_pb2.Timestamp): + Specific run_time for a transfer run to be started. The + requested_run_time must not be in the future. + """ + + class TimeRange(proto.Message): + r"""A specification for a time range, this will request transfer runs + with run_time between start_time (inclusive) and end_time + (exclusive). + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the range of transfer runs. For example, + ``"2017-05-25T00:00:00+00:00"``. The start_time must be + strictly less than the end_time. Creates transfer runs where + run_time is in the range between start_time (inclusive) and + end_time (exclusive). + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the range of transfer runs. For example, + ``"2017-05-30T00:00:00+00:00"``. The end_time must not be in + the future. Creates transfer runs where run_time is in the + range between start_time (inclusive) and end_time + (exclusive). + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + parent = proto.Field( + proto.STRING, + number=1, + ) + requested_time_range = proto.Field( + proto.MESSAGE, + number=3, + oneof='time', + message=TimeRange, + ) + requested_run_time = proto.Field( + proto.MESSAGE, + number=4, + oneof='time', + message=timestamp_pb2.Timestamp, + ) + + +class StartManualTransferRunsResponse(proto.Message): + r"""A response to start manual transfer runs. + Attributes: + runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): + The transfer runs that were created. + """ + + runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=transfer.TransferRun, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py new file mode 100644 index 00000000..1b04cb11 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py @@ -0,0 +1,442 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.bigquery.datatransfer.v1', + manifest={ + 'TransferType', + 'TransferState', + 'EmailPreferences', + 'ScheduleOptions', + 'TransferConfig', + 'TransferRun', + 'TransferMessage', + }, +) + + +class TransferType(proto.Enum): + r"""DEPRECATED. Represents data transfer type.""" + _pb_options = {'deprecated': True} + TRANSFER_TYPE_UNSPECIFIED = 0 + BATCH = 1 + STREAMING = 2 + + +class TransferState(proto.Enum): + r"""Represents data transfer run state.""" + TRANSFER_STATE_UNSPECIFIED = 0 + PENDING = 2 + RUNNING = 3 + SUCCEEDED = 4 + FAILED = 5 + CANCELLED = 6 + + +class EmailPreferences(proto.Message): + r"""Represents preferences for sending email notifications for + transfer run events. + + Attributes: + enable_failure_email (bool): + If true, email notifications will be sent on + transfer run failures. + """ + + enable_failure_email = proto.Field( + proto.BOOL, + number=1, + ) + + +class ScheduleOptions(proto.Message): + r"""Options customizing the data transfer schedule. + Attributes: + disable_auto_scheduling (bool): + If true, automatic scheduling of data + transfer runs for this configuration will be + disabled. The runs can be started on ad-hoc + basis using StartManualTransferRuns API. When + automatic scheduling is disabled, the + TransferConfig.schedule field will be ignored. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Specifies time to start scheduling transfer + runs. The first run will be scheduled at or + after the start time according to a recurrence + pattern defined in the schedule string. The + start time can be changed at any moment. The + time when a data transfer can be trigerred + manually is not limited by this option. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Defines time to stop scheduling transfer + runs. A transfer run cannot be scheduled at or + after the end time. The end time can be changed + at any moment. The time when a data transfer can + be trigerred manually is not limited by this + option. + """ + + disable_auto_scheduling = proto.Field( + proto.BOOL, + number=3, + ) + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class TransferConfig(proto.Message): + r"""Represents a data transfer configuration. A transfer configuration + contains all metadata needed to perform a data transfer. For + example, ``destination_dataset_id`` specifies where data should be + stored. When a new transfer configuration is created, the specified + ``destination_dataset_id`` is created when needed and shared with + the appropriate data source service account. + + Attributes: + name (str): + The resource name of the transfer config. Transfer config + names have the form + ``projects/{project_id}/locations/{region}/transferConfigs/{config_id}``. + Where ``config_id`` is usually a uuid, even though it is not + guaranteed or required. The name is ignored when creating a + transfer config. + destination_dataset_id (str): + The BigQuery target dataset id. + display_name (str): + User specified display name for the data + transfer. + data_source_id (str): + Data source id. Cannot be changed once data + transfer is created. + params (google.protobuf.struct_pb2.Struct): + Parameters specific to each data source. For + more information see the bq tab in the 'Setting + up a data transfer' section for each data + source. For example the parameters for Cloud + Storage transfers are listed here: + https://cloud.google.com/bigquery- + transfer/docs/cloud-storage-transfer#bq + schedule (str): + Data transfer schedule. If the data source does not support + a custom schedule, this should be empty. If it is empty, the + default value for the data source will be used. The + specified times are in UTC. Examples of valid format: + ``1st,3rd monday of month 15:30``, + ``every wed,fri of jan,jun 13:15``, and + ``first sunday of quarter 00:00``. See more explanation + about the format here: + https://cloud.google.com/appengine/docs/flexible/python/scheduling-jobs-with-cron-yaml#the_schedule_format + NOTE: the granularity should be at least 8 hours, or less + frequent. + schedule_options (google.cloud.bigquery_datatransfer_v1.types.ScheduleOptions): + Options customizing the data transfer + schedule. + data_refresh_window_days (int): + The number of days to look back to automatically refresh the + data. For example, if ``data_refresh_window_days = 10``, + then every day BigQuery reingests data for [today-10, + today-1], rather than ingesting data for just [today-1]. + Only valid if the data source supports the feature. Set the + value to 0 to use the default value. + disabled (bool): + Is this config disabled. When set to true, no + runs are scheduled for a given transfer. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Data transfer modification time. + Ignored by server on input. + next_run_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Next time when data transfer + will run. + state (google.cloud.bigquery_datatransfer_v1.types.TransferState): + Output only. State of the most recently + updated transfer run. + user_id (int): + Deprecated. Unique ID of the user on whose + behalf transfer is done. + dataset_region (str): + Output only. Region in which BigQuery dataset + is located. + notification_pubsub_topic (str): + Pub/Sub topic where notifications will be sent after + transfer runs associated with this transfer config finish. + + The format for specifying a pubsub topic is: + ``projects/{project}/topics/{topic}`` + email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): + Email notifications will be sent according to + these preferences to the email address of the + user who owns this transfer config. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + destination_dataset_id = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + data_source_id = proto.Field( + proto.STRING, + number=5, + ) + params = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + schedule = proto.Field( + proto.STRING, + number=7, + ) + schedule_options = proto.Field( + proto.MESSAGE, + number=24, + message='ScheduleOptions', + ) + data_refresh_window_days = proto.Field( + proto.INT32, + number=12, + ) + disabled = proto.Field( + proto.BOOL, + number=13, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + next_run_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=10, + enum='TransferState', + ) + user_id = proto.Field( + proto.INT64, + number=11, + ) + dataset_region = proto.Field( + proto.STRING, + number=14, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=15, + ) + email_preferences = proto.Field( + proto.MESSAGE, + number=18, + message='EmailPreferences', + ) + + +class TransferRun(proto.Message): + r"""Represents a data transfer run. + Attributes: + name (str): + The resource name of the transfer run. Transfer run names + have the form + ``projects/{project_id}/locations/{location}/transferConfigs/{config_id}/runs/{run_id}``. + The name is ignored when creating a transfer run. + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + Minimum time after which a transfer run can + be started. + run_time (google.protobuf.timestamp_pb2.Timestamp): + For batch transfer runs, specifies the date + and time of the data should be ingested. + error_status (google.rpc.status_pb2.Status): + Status of the transfer run. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when transfer run was + started. Parameter ignored by server for input + requests. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when transfer run ended. + Parameter ignored by server for input requests. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the data transfer run + state was updated. + params (google.protobuf.struct_pb2.Struct): + Output only. Parameters specific to each data + source. For more information see the bq tab in + the 'Setting up a data transfer' section for + each data source. For example the parameters for + Cloud Storage transfers are listed here: + https://cloud.google.com/bigquery- + transfer/docs/cloud-storage-transfer#bq + destination_dataset_id (str): + Output only. The BigQuery target dataset id. + data_source_id (str): + Output only. Data source id. + state (google.cloud.bigquery_datatransfer_v1.types.TransferState): + Data transfer run state. Ignored for input + requests. + user_id (int): + Deprecated. Unique ID of the user on whose + behalf transfer is done. + schedule (str): + Output only. Describes the schedule of this transfer run if + it was created as part of a regular schedule. For batch + transfer runs that are scheduled manually, this is empty. + NOTE: the system might choose to delay the schedule + depending on the current load, so ``schedule_time`` doesn't + always match this. + notification_pubsub_topic (str): + Output only. Pub/Sub topic where a notification will be sent + after this transfer run finishes. + + The format for specifying a pubsub topic is: + ``projects/{project}/topics/{topic}`` + email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): + Output only. Email notifications will be sent + according to these preferences to the email + address of the user who owns the transfer config + this run was derived from. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + schedule_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + run_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + error_status = proto.Field( + proto.MESSAGE, + number=21, + message=status_pb2.Status, + ) + start_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + params = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + destination_dataset_id = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + data_source_id = proto.Field( + proto.STRING, + number=7, + ) + state = proto.Field( + proto.ENUM, + number=8, + enum='TransferState', + ) + user_id = proto.Field( + proto.INT64, + number=11, + ) + schedule = proto.Field( + proto.STRING, + number=12, + ) + notification_pubsub_topic = proto.Field( + proto.STRING, + number=23, + ) + email_preferences = proto.Field( + proto.MESSAGE, + number=25, + message='EmailPreferences', + ) + + +class TransferMessage(proto.Message): + r"""Represents a user facing message for a particular data + transfer run. + + Attributes: + message_time (google.protobuf.timestamp_pb2.Timestamp): + Time when message was logged. + severity (google.cloud.bigquery_datatransfer_v1.types.TransferMessage.MessageSeverity): + Message severity. + message_text (str): + Message text. + """ + class MessageSeverity(proto.Enum): + r"""Represents data transfer user facing message severity.""" + MESSAGE_SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + + message_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + severity = proto.Field( + proto.ENUM, + number=2, + enum=MessageSeverity, + ) + message_text = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..ca28a557 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/bigquery_datatransfer_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py new file mode 100644 index 00000000..f7746ab5 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py @@ -0,0 +1,189 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 bigquery_datatransferCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'check_valid_creds': ('name', ), + 'create_transfer_config': ('parent', 'transfer_config', 'authorization_code', 'version_info', 'service_account_name', ), + 'delete_transfer_config': ('name', ), + 'delete_transfer_run': ('name', ), + 'get_data_source': ('name', ), + 'get_transfer_config': ('name', ), + 'get_transfer_run': ('name', ), + 'list_data_sources': ('parent', 'page_token', 'page_size', ), + 'list_transfer_configs': ('parent', 'data_source_ids', 'page_token', 'page_size', ), + 'list_transfer_logs': ('parent', 'page_token', 'page_size', 'message_types', ), + 'list_transfer_runs': ('parent', 'states', 'page_token', 'page_size', 'run_attempt', ), + 'schedule_transfer_runs': ('parent', 'start_time', 'end_time', ), + 'start_manual_transfer_runs': ('parent', 'requested_time_range', 'requested_run_time', ), + 'update_transfer_config': ('transfer_config', 'update_mask', 'authorization_code', 'version_info', 'service_account_name', ), + } + + 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: not a.keyword.value 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=bigquery_datatransferCallTransformer(), +): + """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 bigquery_datatransfer client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..4c0a253d --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-bigquery-datatransfer', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py new file mode 100644 index 00000000..5d484a61 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py @@ -0,0 +1,5087 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import DataTransferServiceAsyncClient +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import DataTransferServiceClient +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import transports +from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.bigquery_datatransfer_v1.types import datatransfer +from google.cloud.bigquery_datatransfer_v1.types import transfer +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataTransferServiceClient._get_default_mtls_endpoint(None) is None + assert DataTransferServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataTransferServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataTransferServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataTransferServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataTransferServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DataTransferServiceClient, + DataTransferServiceAsyncClient, +]) +def test_data_transfer_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataTransferServiceGrpcTransport, "grpc"), + (transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_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", [ + DataTransferServiceClient, + DataTransferServiceAsyncClient, +]) +def test_data_transfer_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' + + +def test_data_transfer_service_client_get_transport_class(): + transport = DataTransferServiceClient.get_transport_class() + available_transports = [ + transports.DataTransferServiceGrpcTransport, + ] + assert transport in available_transports + + transport = DataTransferServiceClient.get_transport_class("grpc") + assert transport == transports.DataTransferServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), + (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DataTransferServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceClient)) +@mock.patch.object(DataTransferServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceAsyncClient)) +def test_data_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(DataTransferServiceClient, '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(DataTransferServiceClient, '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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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() + 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, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc", "true"), + (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc", "false"), + (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DataTransferServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceClient)) +@mock.patch.object(DataTransferServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), + (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), + (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_transfer_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_data_transfer_service_client_client_options_from_dict(): + with mock.patch('google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataTransferServiceClient( + 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, + ) + + +def test_get_data_source(transport: str = 'grpc', request_type=datatransfer.GetDataSourceRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.DataSource( + name='name_value', + data_source_id='data_source_id_value', + display_name='display_name_value', + description='description_value', + client_id='client_id_value', + scopes=['scopes_value'], + transfer_type=transfer.TransferType.BATCH, + supports_multiple_transfers=True, + update_deadline_seconds=2406, + default_schedule='default_schedule_value', + supports_custom_schedule=True, + help_url='help_url_value', + authorization_type=datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE, + data_refresh_type=datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW, + default_data_refresh_window_days=3379, + manual_runs_disabled=True, + ) + response = client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetDataSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.client_id == 'client_id_value' + assert response.scopes == ['scopes_value'] + assert response.transfer_type == transfer.TransferType.BATCH + assert response.supports_multiple_transfers is True + assert response.update_deadline_seconds == 2406 + assert response.default_schedule == 'default_schedule_value' + assert response.supports_custom_schedule is True + assert response.help_url == 'help_url_value' + assert response.authorization_type == datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE + assert response.data_refresh_type == datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW + assert response.default_data_refresh_window_days == 3379 + assert response.manual_runs_disabled is True + + +def test_get_data_source_from_dict(): + test_get_data_source(request_type=dict) + + +def test_get_data_source_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 = DataTransferServiceClient( + 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_data_source), + '__call__') as call: + client.get_data_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetDataSourceRequest() + + +@pytest.mark.asyncio +async def test_get_data_source_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetDataSourceRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource( + name='name_value', + data_source_id='data_source_id_value', + display_name='display_name_value', + description='description_value', + client_id='client_id_value', + scopes=['scopes_value'], + transfer_type=transfer.TransferType.BATCH, + supports_multiple_transfers=True, + update_deadline_seconds=2406, + default_schedule='default_schedule_value', + supports_custom_schedule=True, + help_url='help_url_value', + authorization_type=datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE, + data_refresh_type=datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW, + default_data_refresh_window_days=3379, + manual_runs_disabled=True, + )) + response = await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetDataSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.DataSource) + assert response.name == 'name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.client_id == 'client_id_value' + assert response.scopes == ['scopes_value'] + assert response.transfer_type == transfer.TransferType.BATCH + assert response.supports_multiple_transfers is True + assert response.update_deadline_seconds == 2406 + assert response.default_schedule == 'default_schedule_value' + assert response.supports_custom_schedule is True + assert response.help_url == 'help_url_value' + assert response.authorization_type == datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE + assert response.data_refresh_type == datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW + assert response.default_data_refresh_window_days == 3379 + assert response.manual_runs_disabled is True + + +@pytest.mark.asyncio +async def test_get_data_source_async_from_dict(): + await test_get_data_source_async(request_type=dict) + + +def test_get_data_source_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetDataSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value = datatransfer.DataSource() + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_data_source_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetDataSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource()) + await client.get_data_source(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_data_source_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.DataSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_source( + 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] + assert args[0].name == 'name_value' + + +def test_get_data_source_flattened_error(): + client = DataTransferServiceClient( + 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_data_source( + datatransfer.GetDataSourceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_data_source_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.DataSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_source( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_data_source_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_data_source( + datatransfer.GetDataSourceRequest(), + name='name_value', + ) + + +def test_list_data_sources(transport: str = 'grpc', request_type=datatransfer.ListDataSourcesRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListDataSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListDataSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_sources_from_dict(): + test_list_data_sources(request_type=dict) + + +def test_list_data_sources_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 = DataTransferServiceClient( + 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_data_sources), + '__call__') as call: + client.list_data_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListDataSourcesRequest() + + +@pytest.mark.asyncio +async def test_list_data_sources_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListDataSourcesRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListDataSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_sources_async_from_dict(): + await test_list_data_sources_async(request_type=dict) + + +def test_list_data_sources_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListDataSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + call.return_value = datatransfer.ListDataSourcesResponse() + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_data_sources_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListDataSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse()) + await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_data_sources_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListDataSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_sources( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_data_sources_flattened_error(): + client = DataTransferServiceClient( + 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_data_sources( + datatransfer.ListDataSourcesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_data_sources_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListDataSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_sources( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_data_sources_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_data_sources( + datatransfer.ListDataSourcesRequest(), + parent='parent_value', + ) + + +def test_list_data_sources_pager(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + next_page_token='abc', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + ], + next_page_token='ghi', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_sources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, datatransfer.DataSource) + for i in results) + +def test_list_data_sources_pages(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + next_page_token='abc', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + ], + next_page_token='ghi', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_sources(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_data_sources_async_pager(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + next_page_token='abc', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + ], + next_page_token='ghi', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_sources(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, datatransfer.DataSource) + for i in responses) + +@pytest.mark.asyncio +async def test_list_data_sources_async_pages(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + next_page_token='abc', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[], + next_page_token='def', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + ], + next_page_token='ghi', + ), + datatransfer.ListDataSourcesResponse( + data_sources=[ + datatransfer.DataSource(), + datatransfer.DataSource(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_sources(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_create_transfer_config(transport: str = 'grpc', request_type=datatransfer.CreateTransferConfigRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + destination_dataset_id='destination_dataset_id_value', + ) + response = client.create_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CreateTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +def test_create_transfer_config_from_dict(): + test_create_transfer_config(request_type=dict) + + +def test_create_transfer_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataTransferServiceClient( + 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_config), + '__call__') as call: + client.create_transfer_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CreateTransferConfigRequest() + + +@pytest.mark.asyncio +async def test_create_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.CreateTransferConfigRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + )) + response = await client.create_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CreateTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +@pytest.mark.asyncio +async def test_create_transfer_config_async_from_dict(): + await test_create_transfer_config_async(request_type=dict) + + +def test_create_transfer_config_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.CreateTransferConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_config), + '__call__') as call: + call.return_value = transfer.TransferConfig() + client.create_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_transfer_config_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.CreateTransferConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + await client.create_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_transfer_config_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_transfer_config( + parent='parent_value', + transfer_config=transfer.TransferConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].transfer_config == transfer.TransferConfig(name='name_value') + + +def test_create_transfer_config_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_config( + datatransfer.CreateTransferConfigRequest(), + parent='parent_value', + transfer_config=transfer.TransferConfig(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_transfer_config_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_transfer_config( + parent='parent_value', + transfer_config=transfer.TransferConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].transfer_config == transfer.TransferConfig(name='name_value') + + +@pytest.mark.asyncio +async def test_create_transfer_config_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_config( + datatransfer.CreateTransferConfigRequest(), + parent='parent_value', + transfer_config=transfer.TransferConfig(name='name_value'), + ) + + +def test_update_transfer_config(transport: str = 'grpc', request_type=datatransfer.UpdateTransferConfigRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + destination_dataset_id='destination_dataset_id_value', + ) + response = client.update_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.UpdateTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +def test_update_transfer_config_from_dict(): + test_update_transfer_config(request_type=dict) + + +def test_update_transfer_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataTransferServiceClient( + 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_config), + '__call__') as call: + client.update_transfer_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.UpdateTransferConfigRequest() + + +@pytest.mark.asyncio +async def test_update_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.UpdateTransferConfigRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + )) + response = await client.update_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.UpdateTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +@pytest.mark.asyncio +async def test_update_transfer_config_async_from_dict(): + await test_update_transfer_config_async(request_type=dict) + + +def test_update_transfer_config_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.UpdateTransferConfigRequest() + + request.transfer_config.name = 'transfer_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_config), + '__call__') as call: + call.return_value = transfer.TransferConfig() + client.update_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transfer_config.name=transfer_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_transfer_config_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.UpdateTransferConfigRequest() + + request.transfer_config.name = 'transfer_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + await client.update_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transfer_config.name=transfer_config.name/value', + ) in kw['metadata'] + + +def test_update_transfer_config_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_transfer_config( + transfer_config=transfer.TransferConfig(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] + assert args[0].transfer_config == transfer.TransferConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_transfer_config_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_config( + datatransfer.UpdateTransferConfigRequest(), + transfer_config=transfer.TransferConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_transfer_config_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_transfer_config( + transfer_config=transfer.TransferConfig(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] + assert args[0].transfer_config == transfer.TransferConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_transfer_config_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_config( + datatransfer.UpdateTransferConfigRequest(), + transfer_config=transfer.TransferConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_transfer_config(transport: str = 'grpc', request_type=datatransfer.DeleteTransferConfigRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_transfer_config_from_dict(): + test_delete_transfer_config(request_type=dict) + + +def test_delete_transfer_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataTransferServiceClient( + 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_config), + '__call__') as call: + client.delete_transfer_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.DeleteTransferConfigRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_transfer_config_async_from_dict(): + await test_delete_transfer_config_async(request_type=dict) + + +def test_delete_transfer_config_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.DeleteTransferConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_config), + '__call__') as call: + call.return_value = None + client.delete_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_transfer_config_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.DeleteTransferConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_transfer_config_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_transfer_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_transfer_config_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_config( + datatransfer.DeleteTransferConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_transfer_config_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_transfer_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_transfer_config_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_config( + datatransfer.DeleteTransferConfigRequest(), + name='name_value', + ) + + +def test_get_transfer_config(transport: str = 'grpc', request_type=datatransfer.GetTransferConfigRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + destination_dataset_id='destination_dataset_id_value', + ) + response = client.get_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +def test_get_transfer_config_from_dict(): + test_get_transfer_config(request_type=dict) + + +def test_get_transfer_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataTransferServiceClient( + 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_config), + '__call__') as call: + client.get_transfer_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferConfigRequest() + + +@pytest.mark.asyncio +async def test_get_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetTransferConfigRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( + name='name_value', + display_name='display_name_value', + data_source_id='data_source_id_value', + schedule='schedule_value', + data_refresh_window_days=2543, + disabled=True, + state=transfer.TransferState.PENDING, + user_id=747, + dataset_region='dataset_region_value', + notification_pubsub_topic='notification_pubsub_topic_value', + )) + response = await client.get_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.schedule == 'schedule_value' + assert response.data_refresh_window_days == 2543 + assert response.disabled is True + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.dataset_region == 'dataset_region_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +@pytest.mark.asyncio +async def test_get_transfer_config_async_from_dict(): + await test_get_transfer_config_async(request_type=dict) + + +def test_get_transfer_config_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetTransferConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_config), + '__call__') as call: + call.return_value = transfer.TransferConfig() + client.get_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_transfer_config_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetTransferConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + await client.get_transfer_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_transfer_config_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_transfer_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_transfer_config_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_config( + datatransfer.GetTransferConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_transfer_config_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_transfer_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_transfer_config_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_config( + datatransfer.GetTransferConfigRequest(), + name='name_value', + ) + + +def test_list_transfer_configs(transport: str = 'grpc', request_type=datatransfer.ListTransferConfigsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transfer_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transfer_configs_from_dict(): + test_list_transfer_configs(request_type=dict) + + +def test_list_transfer_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataTransferServiceClient( + 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_configs), + '__call__') as call: + client.list_transfer_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_transfer_configs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferConfigsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transfer_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transfer_configs_async_from_dict(): + await test_list_transfer_configs_async(request_type=dict) + + +def test_list_transfer_configs_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_configs), + '__call__') as call: + call.return_value = datatransfer.ListTransferConfigsResponse() + client.list_transfer_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_transfer_configs_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse()) + await client.list_transfer_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_transfer_configs_flattened(): + client = DataTransferServiceClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_transfer_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_transfer_configs_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_configs( + datatransfer.ListTransferConfigsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_transfer_configs_flattened_async(): + client = DataTransferServiceAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_transfer_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_transfer_configs_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_configs( + datatransfer.ListTransferConfigsRequest(), + parent='parent_value', + ) + + +def test_list_transfer_configs_pager(): + client = DataTransferServiceClient( + 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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[], + next_page_token='def', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_transfer_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, transfer.TransferConfig) + for i in results) + +def test_list_transfer_configs_pages(): + client = DataTransferServiceClient( + 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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[], + next_page_token='def', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transfer_configs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_transfer_configs_async_pager(): + client = DataTransferServiceAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[], + next_page_token='def', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transfer_configs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, transfer.TransferConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_transfer_configs_async_pages(): + client = DataTransferServiceAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[], + next_page_token='def', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferConfigsResponse( + transfer_configs=[ + transfer.TransferConfig(), + transfer.TransferConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_transfer_configs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_schedule_transfer_runs(transport: str = 'grpc', request_type=datatransfer.ScheduleTransferRunsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ScheduleTransferRunsResponse( + ) + response = client.schedule_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ScheduleTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.ScheduleTransferRunsResponse) + + +def test_schedule_transfer_runs_from_dict(): + test_schedule_transfer_runs(request_type=dict) + + +def test_schedule_transfer_runs_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 = DataTransferServiceClient( + 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.schedule_transfer_runs), + '__call__') as call: + client.schedule_transfer_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ScheduleTransferRunsRequest() + + +@pytest.mark.asyncio +async def test_schedule_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ScheduleTransferRunsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse( + )) + response = await client.schedule_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ScheduleTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.ScheduleTransferRunsResponse) + + +@pytest.mark.asyncio +async def test_schedule_transfer_runs_async_from_dict(): + await test_schedule_transfer_runs_async(request_type=dict) + + +def test_schedule_transfer_runs_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ScheduleTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + call.return_value = datatransfer.ScheduleTransferRunsResponse() + client.schedule_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_schedule_transfer_runs_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ScheduleTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse()) + await client.schedule_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_schedule_transfer_runs_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ScheduleTransferRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.schedule_transfer_runs( + parent='parent_value', + start_time=timestamp_pb2.Timestamp(seconds=751), + end_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + assert TimestampRule().to_proto(args[0].end_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_schedule_transfer_runs_flattened_error(): + client = DataTransferServiceClient( + 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.schedule_transfer_runs( + datatransfer.ScheduleTransferRunsRequest(), + parent='parent_value', + start_time=timestamp_pb2.Timestamp(seconds=751), + end_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_schedule_transfer_runs_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.schedule_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ScheduleTransferRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.schedule_transfer_runs( + parent='parent_value', + start_time=timestamp_pb2.Timestamp(seconds=751), + end_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + assert TimestampRule().to_proto(args[0].end_time) == timestamp_pb2.Timestamp(seconds=751) + + +@pytest.mark.asyncio +async def test_schedule_transfer_runs_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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.schedule_transfer_runs( + datatransfer.ScheduleTransferRunsRequest(), + parent='parent_value', + start_time=timestamp_pb2.Timestamp(seconds=751), + end_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_start_manual_transfer_runs(transport: str = 'grpc', request_type=datatransfer.StartManualTransferRunsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_manual_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.StartManualTransferRunsResponse( + ) + response = client.start_manual_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.StartManualTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.StartManualTransferRunsResponse) + + +def test_start_manual_transfer_runs_from_dict(): + test_start_manual_transfer_runs(request_type=dict) + + +def test_start_manual_transfer_runs_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 = DataTransferServiceClient( + 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.start_manual_transfer_runs), + '__call__') as call: + client.start_manual_transfer_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.StartManualTransferRunsRequest() + + +@pytest.mark.asyncio +async def test_start_manual_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.StartManualTransferRunsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_manual_transfer_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.StartManualTransferRunsResponse( + )) + response = await client.start_manual_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.StartManualTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.StartManualTransferRunsResponse) + + +@pytest.mark.asyncio +async def test_start_manual_transfer_runs_async_from_dict(): + await test_start_manual_transfer_runs_async(request_type=dict) + + +def test_start_manual_transfer_runs_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.StartManualTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_manual_transfer_runs), + '__call__') as call: + call.return_value = datatransfer.StartManualTransferRunsResponse() + client.start_manual_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_start_manual_transfer_runs_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.StartManualTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_manual_transfer_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.StartManualTransferRunsResponse()) + await client.start_manual_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_get_transfer_run(transport: str = 'grpc', request_type=datatransfer.GetTransferRunRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferRun( + name='name_value', + data_source_id='data_source_id_value', + state=transfer.TransferState.PENDING, + user_id=747, + schedule='schedule_value', + notification_pubsub_topic='notification_pubsub_topic_value', + destination_dataset_id='destination_dataset_id_value', + ) + response = client.get_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferRun) + assert response.name == 'name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.schedule == 'schedule_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +def test_get_transfer_run_from_dict(): + test_get_transfer_run(request_type=dict) + + +def test_get_transfer_run_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 = DataTransferServiceClient( + 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_run), + '__call__') as call: + client.get_transfer_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferRunRequest() + + +@pytest.mark.asyncio +async def test_get_transfer_run_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetTransferRunRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun( + name='name_value', + data_source_id='data_source_id_value', + state=transfer.TransferState.PENDING, + user_id=747, + schedule='schedule_value', + notification_pubsub_topic='notification_pubsub_topic_value', + )) + response = await client.get_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.GetTransferRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transfer.TransferRun) + assert response.name == 'name_value' + assert response.data_source_id == 'data_source_id_value' + assert response.state == transfer.TransferState.PENDING + assert response.user_id == 747 + assert response.schedule == 'schedule_value' + assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' + + +@pytest.mark.asyncio +async def test_get_transfer_run_async_from_dict(): + await test_get_transfer_run_async(request_type=dict) + + +def test_get_transfer_run_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetTransferRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_run), + '__call__') as call: + call.return_value = transfer.TransferRun() + client.get_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_transfer_run_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.GetTransferRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun()) + await client.get_transfer_run(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_transfer_run_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_transfer_run( + 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] + assert args[0].name == 'name_value' + + +def test_get_transfer_run_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_run( + datatransfer.GetTransferRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_transfer_run_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transfer_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transfer.TransferRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_transfer_run( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_transfer_run_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_run( + datatransfer.GetTransferRunRequest(), + name='name_value', + ) + + +def test_delete_transfer_run(transport: str = 'grpc', request_type=datatransfer.DeleteTransferRunRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferRunRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_transfer_run_from_dict(): + test_delete_transfer_run(request_type=dict) + + +def test_delete_transfer_run_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 = DataTransferServiceClient( + 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_run), + '__call__') as call: + client.delete_transfer_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferRunRequest() + + +@pytest.mark.asyncio +async def test_delete_transfer_run_async(transport: str = 'grpc_asyncio', request_type=datatransfer.DeleteTransferRunRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.DeleteTransferRunRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_transfer_run_async_from_dict(): + await test_delete_transfer_run_async(request_type=dict) + + +def test_delete_transfer_run_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.DeleteTransferRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_run), + '__call__') as call: + call.return_value = None + client.delete_transfer_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_transfer_run_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.DeleteTransferRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_transfer_run(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_transfer_run_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_run), + '__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_transfer_run( + 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] + assert args[0].name == 'name_value' + + +def test_delete_transfer_run_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_run( + datatransfer.DeleteTransferRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_transfer_run_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transfer_run), + '__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_transfer_run( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_transfer_run_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_run( + datatransfer.DeleteTransferRunRequest(), + name='name_value', + ) + + +def test_list_transfer_runs(transport: str = 'grpc', request_type=datatransfer.ListTransferRunsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transfer_runs_from_dict(): + test_list_transfer_runs(request_type=dict) + + +def test_list_transfer_runs_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 = DataTransferServiceClient( + 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_runs), + '__call__') as call: + client.list_transfer_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferRunsRequest() + + +@pytest.mark.asyncio +async def test_list_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferRunsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transfer_runs_async_from_dict(): + await test_list_transfer_runs_async(request_type=dict) + + +def test_list_transfer_runs_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_runs), + '__call__') as call: + call.return_value = datatransfer.ListTransferRunsResponse() + client.list_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_transfer_runs_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse()) + await client.list_transfer_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_transfer_runs_flattened(): + client = DataTransferServiceClient( + 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_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_transfer_runs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_transfer_runs_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_runs( + datatransfer.ListTransferRunsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_transfer_runs_flattened_async(): + client = DataTransferServiceAsyncClient( + 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_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_transfer_runs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_transfer_runs_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_runs( + datatransfer.ListTransferRunsRequest(), + parent='parent_value', + ) + + +def test_list_transfer_runs_pager(): + client = DataTransferServiceClient( + 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_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + transfer.TransferRun(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[], + next_page_token='def', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_transfer_runs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, transfer.TransferRun) + for i in results) + +def test_list_transfer_runs_pages(): + client = DataTransferServiceClient( + 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_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + transfer.TransferRun(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[], + next_page_token='def', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transfer_runs(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_runs_async_pager(): + client = DataTransferServiceAsyncClient( + 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_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + transfer.TransferRun(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[], + next_page_token='def', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transfer_runs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, transfer.TransferRun) + for i in responses) + +@pytest.mark.asyncio +async def test_list_transfer_runs_async_pages(): + client = DataTransferServiceAsyncClient( + 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_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + transfer.TransferRun(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[], + next_page_token='def', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferRunsResponse( + transfer_runs=[ + transfer.TransferRun(), + transfer.TransferRun(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_transfer_runs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_transfer_logs(transport: str = 'grpc', request_type=datatransfer.ListTransferLogsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_logs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferLogsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transfer_logs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferLogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferLogsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transfer_logs_from_dict(): + test_list_transfer_logs(request_type=dict) + + +def test_list_transfer_logs_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 = DataTransferServiceClient( + 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_logs), + '__call__') as call: + client.list_transfer_logs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferLogsRequest() + + +@pytest.mark.asyncio +async def test_list_transfer_logs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferLogsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_logs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transfer_logs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.ListTransferLogsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransferLogsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transfer_logs_async_from_dict(): + await test_list_transfer_logs_async(request_type=dict) + + +def test_list_transfer_logs_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferLogsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_logs), + '__call__') as call: + call.return_value = datatransfer.ListTransferLogsResponse() + client.list_transfer_logs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_transfer_logs_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.ListTransferLogsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transfer_logs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse()) + await client.list_transfer_logs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_transfer_logs_flattened(): + client = DataTransferServiceClient( + 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_logs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferLogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_transfer_logs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_transfer_logs_flattened_error(): + client = DataTransferServiceClient( + 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_transfer_logs( + datatransfer.ListTransferLogsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_transfer_logs_flattened_async(): + client = DataTransferServiceAsyncClient( + 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_logs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.ListTransferLogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_transfer_logs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_transfer_logs_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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_transfer_logs( + datatransfer.ListTransferLogsRequest(), + parent='parent_value', + ) + + +def test_list_transfer_logs_pager(): + client = DataTransferServiceClient( + 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_logs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[], + next_page_token='def', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_transfer_logs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, transfer.TransferMessage) + for i in results) + +def test_list_transfer_logs_pages(): + client = DataTransferServiceClient( + 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_logs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[], + next_page_token='def', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transfer_logs(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_logs_async_pager(): + client = DataTransferServiceAsyncClient( + 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_logs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[], + next_page_token='def', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transfer_logs(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, transfer.TransferMessage) + for i in responses) + +@pytest.mark.asyncio +async def test_list_transfer_logs_async_pages(): + client = DataTransferServiceAsyncClient( + 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_logs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + next_page_token='abc', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[], + next_page_token='def', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + ], + next_page_token='ghi', + ), + datatransfer.ListTransferLogsResponse( + transfer_messages=[ + transfer.TransferMessage(), + transfer.TransferMessage(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_transfer_logs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_check_valid_creds(transport: str = 'grpc', request_type=datatransfer.CheckValidCredsRequest): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.CheckValidCredsResponse( + has_valid_creds=True, + ) + response = client.check_valid_creds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CheckValidCredsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.CheckValidCredsResponse) + assert response.has_valid_creds is True + + +def test_check_valid_creds_from_dict(): + test_check_valid_creds(request_type=dict) + + +def test_check_valid_creds_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 = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + client.check_valid_creds() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CheckValidCredsRequest() + + +@pytest.mark.asyncio +async def test_check_valid_creds_async(transport: str = 'grpc_asyncio', request_type=datatransfer.CheckValidCredsRequest): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse( + has_valid_creds=True, + )) + response = await client.check_valid_creds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datatransfer.CheckValidCredsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datatransfer.CheckValidCredsResponse) + assert response.has_valid_creds is True + + +@pytest.mark.asyncio +async def test_check_valid_creds_async_from_dict(): + await test_check_valid_creds_async(request_type=dict) + + +def test_check_valid_creds_field_headers(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.CheckValidCredsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + call.return_value = datatransfer.CheckValidCredsResponse() + client.check_valid_creds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_check_valid_creds_field_headers_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datatransfer.CheckValidCredsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse()) + await client.check_valid_creds(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_check_valid_creds_flattened(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.CheckValidCredsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.check_valid_creds( + 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] + assert args[0].name == 'name_value' + + +def test_check_valid_creds_flattened_error(): + client = DataTransferServiceClient( + 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.check_valid_creds( + datatransfer.CheckValidCredsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_check_valid_creds_flattened_async(): + client = DataTransferServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_valid_creds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datatransfer.CheckValidCredsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.check_valid_creds( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_check_valid_creds_flattened_error_async(): + client = DataTransferServiceAsyncClient( + 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.check_valid_creds( + datatransfer.CheckValidCredsRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataTransferServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataTransferServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataTransferServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataTransferServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataTransferServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataTransferServiceGrpcTransport, + transports.DataTransferServiceGrpcAsyncIOTransport, +]) +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() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataTransferServiceGrpcTransport, + ) + +def test_data_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.DataTransferServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_transfer_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataTransferServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_data_source', + 'list_data_sources', + 'create_transfer_config', + 'update_transfer_config', + 'delete_transfer_config', + 'get_transfer_config', + 'list_transfer_configs', + 'schedule_transfer_runs', + 'start_manual_transfer_runs', + 'get_transfer_run', + 'delete_transfer_run', + 'list_transfer_runs', + 'list_transfer_logs', + 'check_valid_creds', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_data_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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataTransferServiceTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_data_transfer_service_base_transport_with_credentials_file_old_google_auth(): + # 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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataTransferServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_data_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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataTransferServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_data_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) + DataTransferServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_data_transfer_service_auth_adc_old_google_auth(): + # 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) + DataTransferServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataTransferServiceGrpcTransport, + transports.DataTransferServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_data_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.DataTransferServiceGrpcTransport, + transports.DataTransferServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_data_transfer_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DataTransferServiceGrpcTransport, grpc_helpers), + (transports.DataTransferServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_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( + "bigquerydatatransfer.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="bigquerydatatransfer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) +def test_data_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_data_transfer_service_host_no_port(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='bigquerydatatransfer.googleapis.com'), + ) + assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' + + +def test_data_transfer_service_host_with_port(): + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='bigquerydatatransfer.googleapis.com:8000'), + ) + assert client.transport._host == 'bigquerydatatransfer.googleapis.com:8000' + +def test_data_transfer_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataTransferServiceGrpcTransport( + 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_data_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.DataTransferServiceGrpcAsyncIOTransport( + 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.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) +def test_data_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.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) +def test_data_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_data_source_path(): + project = "squid" + data_source = "clam" + expected = "projects/{project}/dataSources/{data_source}".format(project=project, data_source=data_source, ) + actual = DataTransferServiceClient.data_source_path(project, data_source) + assert expected == actual + + +def test_parse_data_source_path(): + expected = { + "project": "whelk", + "data_source": "octopus", + } + path = DataTransferServiceClient.data_source_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_data_source_path(path) + assert expected == actual + +def test_run_path(): + project = "oyster" + transfer_config = "nudibranch" + run = "cuttlefish" + expected = "projects/{project}/transferConfigs/{transfer_config}/runs/{run}".format(project=project, transfer_config=transfer_config, run=run, ) + actual = DataTransferServiceClient.run_path(project, transfer_config, run) + assert expected == actual + + +def test_parse_run_path(): + expected = { + "project": "mussel", + "transfer_config": "winkle", + "run": "nautilus", + } + path = DataTransferServiceClient.run_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_run_path(path) + assert expected == actual + +def test_transfer_config_path(): + project = "scallop" + transfer_config = "abalone" + expected = "projects/{project}/transferConfigs/{transfer_config}".format(project=project, transfer_config=transfer_config, ) + actual = DataTransferServiceClient.transfer_config_path(project, transfer_config) + assert expected == actual + + +def test_parse_transfer_config_path(): + expected = { + "project": "squid", + "transfer_config": "clam", + } + path = DataTransferServiceClient.transfer_config_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_transfer_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataTransferServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DataTransferServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataTransferServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DataTransferServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataTransferServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DataTransferServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DataTransferServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DataTransferServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataTransferServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DataTransferServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataTransferServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DataTransferServiceTransport, '_prep_wrapped_messages') as prep: + client = DataTransferServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataTransferServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DataTransferServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 330e31423cd7517a27bbd6ab81c8fb6ed03cb7da Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 19 Aug 2021 16:36:07 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../data_transfer_service/async_client.py | 4 +- .../services/data_transfer_service/client.py | 4 +- .../data_transfer_service/transports/grpc.py | 4 +- .../transports/grpc_asyncio.py | 4 +- .../types/datatransfer.py | 7 +- .../types/transfer.py | 43 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - .../data_transfer_service.rst | 10 - .../bigquery_datatransfer_v1/services.rst | 6 - .../docs/bigquery_datatransfer_v1/types.rst | 7 - owl-bot-staging/v1/docs/conf.py | 376 -- owl-bot-staging/v1/docs/index.rst | 7 - .../cloud/bigquery_datatransfer/__init__.py | 83 - .../cloud/bigquery_datatransfer/py.typed | 2 - .../bigquery_datatransfer_v1/__init__.py | 84 - .../gapic_metadata.json | 163 - .../cloud/bigquery_datatransfer_v1/py.typed | 2 - .../services/__init__.py | 15 - .../data_transfer_service/__init__.py | 22 - .../data_transfer_service/async_client.py | 1432 ----- .../services/data_transfer_service/client.py | 1572 ----- .../services/data_transfer_service/pagers.py | 507 -- .../transports/__init__.py | 33 - .../data_transfer_service/transports/base.py | 422 -- .../data_transfer_service/transports/grpc.py | 615 -- .../transports/grpc_asyncio.py | 619 -- .../types/__init__.py | 82 - .../types/datatransfer.py | 1023 ---- .../types/transfer.py | 442 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - ...fixup_bigquery_datatransfer_v1_keywords.py | 189 - owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../bigquery_datatransfer_v1/__init__.py | 16 - .../test_data_transfer_service.py | 5087 ----------------- 40 files changed, 40 insertions(+), 13147 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst delete mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py delete mode 100644 owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py diff --git a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py index 7f502338..fc73542b 100644 --- a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py +++ b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py @@ -724,8 +724,8 @@ async def list_transfer_configs( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransferConfigsAsyncPager: - r"""Returns information about all data transfers in the - project. + r"""Returns information about all transfer configs owned + by a project in the specified location. Args: request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest`): diff --git a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py index 637b0cdf..e735a19d 100644 --- a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py +++ b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py @@ -897,8 +897,8 @@ def list_transfer_configs( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListTransferConfigsPager: - r"""Returns information about all data transfers in the - project. + r"""Returns information about all transfer configs owned + by a project in the specified location. Args: request (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): diff --git a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py index 6f431d2a..b0041dff 100644 --- a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py +++ b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py @@ -401,8 +401,8 @@ def list_transfer_configs( ]: r"""Return a callable for the list transfer configs method over gRPC. - Returns information about all data transfers in the - project. + Returns information about all transfer configs owned + by a project in the specified location. Returns: Callable[[~.ListTransferConfigsRequest], diff --git a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py index a5f7d8f4..b7c0d612 100644 --- a/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py +++ b/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py @@ -415,8 +415,8 @@ def list_transfer_configs( ]: r"""Return a callable for the list transfer configs method over gRPC. - Returns information about all data transfers in the - project. + Returns information about all transfer configs owned + by a project in the specified location. Returns: Callable[[~.ListTransferConfigsRequest], diff --git a/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py b/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py index d9869c0d..0e043788 100644 --- a/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py +++ b/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py @@ -731,13 +731,14 @@ class TimeRange(proto.Message): Start time of the range of transfer runs. For example, ``"2017-05-25T00:00:00+00:00"``. The start_time must be strictly less than the end_time. Creates transfer runs where - run_time is in the range betwen start_time (inclusive) and - end_time (exlusive). + run_time is in the range between start_time (inclusive) and + end_time (exclusive). end_time (google.protobuf.timestamp_pb2.Timestamp): End time of the range of transfer runs. For example, ``"2017-05-30T00:00:00+00:00"``. The end_time must not be in the future. Creates transfer runs where run_time is in the - range betwen start_time (inclusive) and end_time (exlusive). + range between start_time (inclusive) and end_time + (exclusive). """ start_time = proto.Field( diff --git a/google/cloud/bigquery_datatransfer_v1/types/transfer.py b/google/cloud/bigquery_datatransfer_v1/types/transfer.py index 5e04fc7d..76a5856f 100644 --- a/google/cloud/bigquery_datatransfer_v1/types/transfer.py +++ b/google/cloud/bigquery_datatransfer_v1/types/transfer.py @@ -108,13 +108,11 @@ class TransferConfig(proto.Message): Attributes: name (str): The resource name of the transfer config. Transfer config - names have the form of + names have the form ``projects/{project_id}/locations/{region}/transferConfigs/{config_id}``. - The name is automatically generated based on the config_id - specified in CreateTransferConfigRequest along with - project_id and region. If config_id is not provided, usually - a uuid, even though it is not guaranteed or required, will - be generated for config_id. + Where ``config_id`` is usually a uuid, even though it is not + guaranteed or required. The name is ignored when creating a + transfer config. destination_dataset_id (str): The BigQuery target dataset id. display_name (str): @@ -124,7 +122,13 @@ class TransferConfig(proto.Message): Data source id. Cannot be changed once data transfer is created. params (google.protobuf.struct_pb2.Struct): - Data transfer specific parameters. + Parameters specific to each data source. For + more information see the bq tab in the 'Setting + up a data transfer' section for each data + source. For example the parameters for Cloud + Storage transfers are listed here: + https://cloud.google.com/bigquery- + transfer/docs/cloud-storage-transfer#bq schedule (str): Data transfer schedule. If the data source does not support a custom schedule, this should be empty. If it is empty, the @@ -166,9 +170,11 @@ class TransferConfig(proto.Message): Output only. Region in which BigQuery dataset is located. notification_pubsub_topic (str): - Pub/Sub topic where notifications will be - sent after transfer runs associated with this - transfer config finish. + Pub/Sub topic where notifications will be sent after + transfer runs associated with this transfer config finish. + + The format for specifying a pubsub topic is: + ``projects/{project}/topics/{topic}`` email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): Email notifications will be sent according to these preferences to the email address of the @@ -224,8 +230,13 @@ class TransferRun(proto.Message): Output only. Last time the data transfer run state was updated. params (google.protobuf.struct_pb2.Struct): - Output only. Data transfer specific - parameters. + Output only. Parameters specific to each data + source. For more information see the bq tab in + the 'Setting up a data transfer' section for + each data source. For example the parameters for + Cloud Storage transfers are listed here: + https://cloud.google.com/bigquery- + transfer/docs/cloud-storage-transfer#bq destination_dataset_id (str): Output only. The BigQuery target dataset id. data_source_id (str): @@ -244,9 +255,11 @@ class TransferRun(proto.Message): depending on the current load, so ``schedule_time`` doesn't always match this. notification_pubsub_topic (str): - Output only. Pub/Sub topic where a - notification will be sent after this transfer - run finishes + Output only. Pub/Sub topic where a notification will be sent + after this transfer run finishes. + + The format for specifying a pubsub topic is: + ``projects/{project}/topics/{topic}`` email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): Output only. Email notifications will be sent according to these preferences to the email diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 63daceaf..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/bigquery_datatransfer/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index c429b83c..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/bigquery_datatransfer *.py -recursive-include google/cloud/bigquery_datatransfer_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index a68e336f..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Bigquery Datatransfer 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 Bigquery Datatransfer API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst deleted file mode 100644 index 480f43ed..00000000 --- a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/data_transfer_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DataTransferService -------------------------------------- - -.. automodule:: google.cloud.bigquery_datatransfer_v1.services.data_transfer_service - :members: - :inherited-members: - -.. automodule:: google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst deleted file mode 100644 index 37a71a43..00000000 --- a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Bigquery Datatransfer v1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - data_transfer_service diff --git a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst b/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst deleted file mode 100644 index d46636eb..00000000 --- a/owl-bot-staging/v1/docs/bigquery_datatransfer_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Bigquery Datatransfer v1 API -=================================================== - -.. automodule:: google.cloud.bigquery_datatransfer_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 7ff9493b..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-bigquery-datatransfer 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-bigquery-datatransfer" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-bigquery-datatransfer-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 = [ - ( - master_doc, - "google-cloud-bigquery-datatransfer.tex", - u"google-cloud-bigquery-datatransfer 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 = [ - ( - master_doc, - "google-cloud-bigquery-datatransfer", - u"Google Cloud Bigquery Datatransfer 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 = [ - ( - master_doc, - "google-cloud-bigquery-datatransfer", - u"google-cloud-bigquery-datatransfer Documentation", - author, - "google-cloud-bigquery-datatransfer", - "GAPIC library for Google Cloud Bigquery Datatransfer API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 3bc1adcc..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - bigquery_datatransfer_v1/services - bigquery_datatransfer_v1/types diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py deleted file mode 100644 index f364f477..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/__init__.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.bigquery_datatransfer_v1.services.data_transfer_service.client import DataTransferServiceClient -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.async_client import DataTransferServiceAsyncClient - -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CheckValidCredsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CheckValidCredsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import CreateTransferConfigRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DataSource -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DataSourceParameter -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DeleteTransferConfigRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import DeleteTransferRunRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetDataSourceRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetTransferConfigRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import GetTransferRunRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListDataSourcesRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListDataSourcesResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferConfigsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferConfigsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferLogsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferLogsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferRunsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ListTransferRunsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ScheduleTransferRunsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import ScheduleTransferRunsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import StartManualTransferRunsRequest -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import StartManualTransferRunsResponse -from google.cloud.bigquery_datatransfer_v1.types.datatransfer import UpdateTransferConfigRequest -from google.cloud.bigquery_datatransfer_v1.types.transfer import EmailPreferences -from google.cloud.bigquery_datatransfer_v1.types.transfer import ScheduleOptions -from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferConfig -from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferMessage -from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferRun -from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferState -from google.cloud.bigquery_datatransfer_v1.types.transfer import TransferType - -__all__ = ('DataTransferServiceClient', - 'DataTransferServiceAsyncClient', - 'CheckValidCredsRequest', - 'CheckValidCredsResponse', - 'CreateTransferConfigRequest', - 'DataSource', - 'DataSourceParameter', - 'DeleteTransferConfigRequest', - 'DeleteTransferRunRequest', - 'GetDataSourceRequest', - 'GetTransferConfigRequest', - 'GetTransferRunRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'ListTransferConfigsRequest', - 'ListTransferConfigsResponse', - 'ListTransferLogsRequest', - 'ListTransferLogsResponse', - 'ListTransferRunsRequest', - 'ListTransferRunsResponse', - 'ScheduleTransferRunsRequest', - 'ScheduleTransferRunsResponse', - 'StartManualTransferRunsRequest', - 'StartManualTransferRunsResponse', - 'UpdateTransferConfigRequest', - 'EmailPreferences', - 'ScheduleOptions', - 'TransferConfig', - 'TransferMessage', - 'TransferRun', - 'TransferState', - 'TransferType', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed deleted file mode 100644 index 1bd9d383..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-bigquery-datatransfer package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py deleted file mode 100644 index b93e0e2b..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/__init__.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.data_transfer_service import DataTransferServiceClient -from .services.data_transfer_service import DataTransferServiceAsyncClient - -from .types.datatransfer import CheckValidCredsRequest -from .types.datatransfer import CheckValidCredsResponse -from .types.datatransfer import CreateTransferConfigRequest -from .types.datatransfer import DataSource -from .types.datatransfer import DataSourceParameter -from .types.datatransfer import DeleteTransferConfigRequest -from .types.datatransfer import DeleteTransferRunRequest -from .types.datatransfer import GetDataSourceRequest -from .types.datatransfer import GetTransferConfigRequest -from .types.datatransfer import GetTransferRunRequest -from .types.datatransfer import ListDataSourcesRequest -from .types.datatransfer import ListDataSourcesResponse -from .types.datatransfer import ListTransferConfigsRequest -from .types.datatransfer import ListTransferConfigsResponse -from .types.datatransfer import ListTransferLogsRequest -from .types.datatransfer import ListTransferLogsResponse -from .types.datatransfer import ListTransferRunsRequest -from .types.datatransfer import ListTransferRunsResponse -from .types.datatransfer import ScheduleTransferRunsRequest -from .types.datatransfer import ScheduleTransferRunsResponse -from .types.datatransfer import StartManualTransferRunsRequest -from .types.datatransfer import StartManualTransferRunsResponse -from .types.datatransfer import UpdateTransferConfigRequest -from .types.transfer import EmailPreferences -from .types.transfer import ScheduleOptions -from .types.transfer import TransferConfig -from .types.transfer import TransferMessage -from .types.transfer import TransferRun -from .types.transfer import TransferState -from .types.transfer import TransferType - -__all__ = ( - 'DataTransferServiceAsyncClient', -'CheckValidCredsRequest', -'CheckValidCredsResponse', -'CreateTransferConfigRequest', -'DataSource', -'DataSourceParameter', -'DataTransferServiceClient', -'DeleteTransferConfigRequest', -'DeleteTransferRunRequest', -'EmailPreferences', -'GetDataSourceRequest', -'GetTransferConfigRequest', -'GetTransferRunRequest', -'ListDataSourcesRequest', -'ListDataSourcesResponse', -'ListTransferConfigsRequest', -'ListTransferConfigsResponse', -'ListTransferLogsRequest', -'ListTransferLogsResponse', -'ListTransferRunsRequest', -'ListTransferRunsResponse', -'ScheduleOptions', -'ScheduleTransferRunsRequest', -'ScheduleTransferRunsResponse', -'StartManualTransferRunsRequest', -'StartManualTransferRunsResponse', -'TransferConfig', -'TransferMessage', -'TransferRun', -'TransferState', -'TransferType', -'UpdateTransferConfigRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json deleted file mode 100644 index 75ee9340..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/gapic_metadata.json +++ /dev/null @@ -1,163 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.bigquery_datatransfer_v1", - "protoPackage": "google.cloud.bigquery.datatransfer.v1", - "schema": "1.0", - "services": { - "DataTransferService": { - "clients": { - "grpc": { - "libraryClient": "DataTransferServiceClient", - "rpcs": { - "CheckValidCreds": { - "methods": [ - "check_valid_creds" - ] - }, - "CreateTransferConfig": { - "methods": [ - "create_transfer_config" - ] - }, - "DeleteTransferConfig": { - "methods": [ - "delete_transfer_config" - ] - }, - "DeleteTransferRun": { - "methods": [ - "delete_transfer_run" - ] - }, - "GetDataSource": { - "methods": [ - "get_data_source" - ] - }, - "GetTransferConfig": { - "methods": [ - "get_transfer_config" - ] - }, - "GetTransferRun": { - "methods": [ - "get_transfer_run" - ] - }, - "ListDataSources": { - "methods": [ - "list_data_sources" - ] - }, - "ListTransferConfigs": { - "methods": [ - "list_transfer_configs" - ] - }, - "ListTransferLogs": { - "methods": [ - "list_transfer_logs" - ] - }, - "ListTransferRuns": { - "methods": [ - "list_transfer_runs" - ] - }, - "ScheduleTransferRuns": { - "methods": [ - "schedule_transfer_runs" - ] - }, - "StartManualTransferRuns": { - "methods": [ - "start_manual_transfer_runs" - ] - }, - "UpdateTransferConfig": { - "methods": [ - "update_transfer_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataTransferServiceAsyncClient", - "rpcs": { - "CheckValidCreds": { - "methods": [ - "check_valid_creds" - ] - }, - "CreateTransferConfig": { - "methods": [ - "create_transfer_config" - ] - }, - "DeleteTransferConfig": { - "methods": [ - "delete_transfer_config" - ] - }, - "DeleteTransferRun": { - "methods": [ - "delete_transfer_run" - ] - }, - "GetDataSource": { - "methods": [ - "get_data_source" - ] - }, - "GetTransferConfig": { - "methods": [ - "get_transfer_config" - ] - }, - "GetTransferRun": { - "methods": [ - "get_transfer_run" - ] - }, - "ListDataSources": { - "methods": [ - "list_data_sources" - ] - }, - "ListTransferConfigs": { - "methods": [ - "list_transfer_configs" - ] - }, - "ListTransferLogs": { - "methods": [ - "list_transfer_logs" - ] - }, - "ListTransferRuns": { - "methods": [ - "list_transfer_runs" - ] - }, - "ScheduleTransferRuns": { - "methods": [ - "schedule_transfer_runs" - ] - }, - "StartManualTransferRuns": { - "methods": [ - "start_manual_transfer_runs" - ] - }, - "UpdateTransferConfig": { - "methods": [ - "update_transfer_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed deleted file mode 100644 index 1bd9d383..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-bigquery-datatransfer package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py deleted file mode 100644 index 920fa888..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DataTransferServiceClient -from .async_client import DataTransferServiceAsyncClient - -__all__ = ( - 'DataTransferServiceClient', - 'DataTransferServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py deleted file mode 100644 index 32c0261d..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/async_client.py +++ /dev/null @@ -1,1432 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources -import warnings - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport -from .client import DataTransferServiceClient - - -class DataTransferServiceAsyncClient: - """The Google BigQuery Data Transfer Service API enables - BigQuery users to configure the transfer of their data from - other Google Products into BigQuery. This service contains - methods that are end user exposed. It backs up the frontend. - """ - - _client: DataTransferServiceClient - - DEFAULT_ENDPOINT = DataTransferServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DataTransferServiceClient.DEFAULT_MTLS_ENDPOINT - - data_source_path = staticmethod(DataTransferServiceClient.data_source_path) - parse_data_source_path = staticmethod(DataTransferServiceClient.parse_data_source_path) - run_path = staticmethod(DataTransferServiceClient.run_path) - parse_run_path = staticmethod(DataTransferServiceClient.parse_run_path) - transfer_config_path = staticmethod(DataTransferServiceClient.transfer_config_path) - parse_transfer_config_path = staticmethod(DataTransferServiceClient.parse_transfer_config_path) - common_billing_account_path = staticmethod(DataTransferServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataTransferServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DataTransferServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DataTransferServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DataTransferServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DataTransferServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DataTransferServiceClient.common_project_path) - parse_common_project_path = staticmethod(DataTransferServiceClient.parse_common_project_path) - common_location_path = staticmethod(DataTransferServiceClient.common_location_path) - parse_common_location_path = staticmethod(DataTransferServiceClient.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: - DataTransferServiceAsyncClient: The constructed client. - """ - return DataTransferServiceClient.from_service_account_info.__func__(DataTransferServiceAsyncClient, 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: - DataTransferServiceAsyncClient: The constructed client. - """ - return DataTransferServiceClient.from_service_account_file.__func__(DataTransferServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DataTransferServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataTransferServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DataTransferServiceClient).get_transport_class, type(DataTransferServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DataTransferServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data 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 (Union[str, ~.DataTransferServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DataTransferServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_data_source(self, - request: datatransfer.GetDataSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.DataSource: - r"""Retrieves a supported data source and returns its - settings, which can be used for UI rendering. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetDataSourceRequest`): - The request object. A request to get data source info. - name (:class:`str`): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/dataSources/{data_source_id}`` - or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.DataSource: - Represents data source metadata. - Metadata is sufficient to render UI and - request proper OAuth tokens. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.GetDataSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_data_source, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_data_sources(self, - request: datatransfer.ListDataSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataSourcesAsyncPager: - r"""Lists supported data sources and returns their - settings, which can be used for UI rendering. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesRequest`): - The request object. Request to list supported data - sources and their data transfer settings. - parent (:class:`str`): - Required. The BigQuery project id for which data sources - should be returned. Must be in the form: - ``projects/{project_id}`` or - \`projects/{project_id}/locations/{location_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListDataSourcesAsyncPager: - Returns list of supported data - sources and their metadata. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.ListDataSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_data_sources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDataSourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_transfer_config(self, - request: datatransfer.CreateTransferConfigRequest = None, - *, - parent: str = None, - transfer_config: transfer.TransferConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Creates a new data transfer configuration. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.CreateTransferConfigRequest`): - The request object. A request to create a data transfer - configuration. If new credentials are needed for this - transfer configuration, an authorization code must be - provided. If an authorization code is provided, the - transfer configuration will be associated with the user - id corresponding to the authorization code. Otherwise, - the transfer configuration will be associated with the - calling user. - parent (:class:`str`): - Required. The BigQuery project id where the transfer - configuration should be created. Must be in the format - projects/{project_id}/locations/{location_id} or - projects/{project_id}. If specified location and - location of the destination bigquery dataset do not - match - the request will fail. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transfer_config (:class:`google.cloud.bigquery_datatransfer_v1.types.TransferConfig`): - Required. Data transfer configuration - to create. - - This corresponds to the ``transfer_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transfer_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.CreateTransferConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transfer_config is not None: - request.transfer_config = transfer_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_transfer_config, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_transfer_config(self, - request: datatransfer.UpdateTransferConfigRequest = None, - *, - transfer_config: transfer.TransferConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Updates a data transfer configuration. - All fields must be set, even if they are not updated. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.UpdateTransferConfigRequest`): - The request object. A request to update a transfer - configuration. To update the user id of the transfer - configuration, an authorization code needs to be - provided. - transfer_config (:class:`google.cloud.bigquery_datatransfer_v1.types.TransferConfig`): - Required. Data transfer configuration - to create. - - This corresponds to the ``transfer_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Required list of fields to - be updated in this request. - - 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.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transfer_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.UpdateTransferConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transfer_config is not None: - request.transfer_config = transfer_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_transfer_config, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transfer_config.name", request.transfer_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_transfer_config(self, - request: datatransfer.DeleteTransferConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a data transfer configuration, - including any associated transfer runs and logs. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.DeleteTransferConfigRequest`): - The request object. A request to delete data transfer - information. All associated transfer runs and log - messages will be deleted as well. - name (:class:`str`): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.DeleteTransferConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_transfer_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_transfer_config(self, - request: datatransfer.GetTransferConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Returns information about a data transfer config. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetTransferConfigRequest`): - The request object. A request to get data transfer - information. - name (:class:`str`): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.GetTransferConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_transfer_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_transfer_configs(self, - request: datatransfer.ListTransferConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferConfigsAsyncPager: - r"""Returns information about all transfer configs owned - by a project in the specified location. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest`): - The request object. A request to list data transfers - configured for a BigQuery project. - parent (:class:`str`): - Required. The BigQuery project id for which data sources - should be returned: ``projects/{project_id}`` or - ``projects/{project_id}/locations/{location_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferConfigsAsyncPager: - The returned list of pipelines in the - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.ListTransferConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_transfer_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTransferConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def schedule_transfer_runs(self, - request: datatransfer.ScheduleTransferRunsRequest = None, - *, - parent: str = None, - start_time: timestamp_pb2.Timestamp = None, - end_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.ScheduleTransferRunsResponse: - r"""Creates transfer runs for a time range [start_time, end_time]. - For each date - or whatever granularity the data source supports - - in the range, one transfer run is created. Note that runs are - created per UTC time in the time range. DEPRECATED: use - StartManualTransferRuns instead. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsRequest`): - The request object. A request to schedule transfer runs - for a time range. - parent (:class:`str`): - Required. Transfer configuration name in the form: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. Start time of the range of transfer runs. For - example, ``"2017-05-25T00:00:00+00:00"``. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - end_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. End time of the range of transfer runs. For - example, ``"2017-05-30T00:00:00+00:00"``. - - This corresponds to the ``end_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse: - A response to schedule transfer runs - for a time range. - - """ - warnings.warn("DataTransferServiceAsyncClient.schedule_transfer_runs is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, start_time, end_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.ScheduleTransferRunsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if start_time is not None: - request.start_time = start_time - if end_time is not None: - request.end_time = end_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.schedule_transfer_runs, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def start_manual_transfer_runs(self, - request: datatransfer.StartManualTransferRunsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.StartManualTransferRunsResponse: - r"""Start manual transfer runs to be executed now with schedule_time - equal to current time. The transfer runs can be created for a - time range where the run_time is between start_time (inclusive) - and end_time (exclusive), or for a specific run_time. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest`): - The request object. A request to start manual transfer - runs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.bigquery_datatransfer_v1.types.StartManualTransferRunsResponse: - A response to start manual transfer - runs. - - """ - # Create or coerce a protobuf request object. - request = datatransfer.StartManualTransferRunsRequest(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.start_manual_transfer_runs, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_transfer_run(self, - request: datatransfer.GetTransferRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferRun: - r"""Returns information about the particular transfer - run. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.GetTransferRunRequest`): - The request object. A request to get data transfer run - information. - name (:class:`str`): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferRun: - Represents a data transfer run. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.GetTransferRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_transfer_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_transfer_run(self, - request: datatransfer.DeleteTransferRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified transfer run. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.DeleteTransferRunRequest`): - The request object. A request to delete data transfer - run information. - name (:class:`str`): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.DeleteTransferRunRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_transfer_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_transfer_runs(self, - request: datatransfer.ListTransferRunsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferRunsAsyncPager: - r"""Returns information about running and completed jobs. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest`): - The request object. A request to list data transfer - runs. UI can use this method to show/filter specific - data transfer runs. The data source can use this method - to request all scheduled transfer runs. - parent (:class:`str`): - Required. Name of transfer configuration for which - transfer runs should be retrieved. Format of transfer - configuration resource name is: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferRunsAsyncPager: - The returned list of pipelines in the - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.ListTransferRunsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_transfer_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTransferRunsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_transfer_logs(self, - request: datatransfer.ListTransferLogsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferLogsAsyncPager: - r"""Returns user facing log messages for the data - transfer run. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsRequest`): - The request object. A request to get user facing log - messages associated with data transfer run. - parent (:class:`str`): - Required. Transfer run name in the form: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferLogsAsyncPager: - The returned list transfer run - messages. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.ListTransferLogsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_transfer_logs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTransferLogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def check_valid_creds(self, - request: datatransfer.CheckValidCredsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.CheckValidCredsResponse: - r"""Returns true if valid credentials exist for the given - data source and requesting user. - Some data sources doesn't support service account, so we - need to talk to them on behalf of the end user. This API - just checks whether we have OAuth token for the - particular user, which is a pre-requisite before user - can create a transfer config. - - Args: - request (:class:`google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsRequest`): - The request object. A request to determine whether the - user has valid credentials. This method is used to limit - the number of OAuth popups in the user interface. The - user id is inferred from the API call context. - If the data source has the Google+ authorization type, - this method returns false, as it cannot be determined - whether the credentials are already valid merely based - on the user id. - name (:class:`str`): - Required. The data source in the form: - ``projects/{project_id}/dataSources/{data_source_id}`` - or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsResponse: - A response indicating whether the - credentials exist and are valid. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datatransfer.CheckValidCredsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.check_valid_creds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-bigquery-datatransfer", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataTransferServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py deleted file mode 100644 index c765505c..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py +++ /dev/null @@ -1,1572 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources -import warnings - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DataTransferServiceGrpcTransport -from .transports.grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport - - -class DataTransferServiceClientMeta(type): - """Metaclass for the DataTransferService 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[DataTransferServiceTransport]] - _transport_registry["grpc"] = DataTransferServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DataTransferServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DataTransferServiceTransport]: - """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 DataTransferServiceClient(metaclass=DataTransferServiceClientMeta): - """The Google BigQuery Data Transfer Service API enables - BigQuery users to configure the transfer of their data from - other Google Products into BigQuery. This service contains - methods that are end user exposed. It backs up the frontend. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "bigquerydatatransfer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DataTransferServiceClient: 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: - DataTransferServiceClient: 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) -> DataTransferServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DataTransferServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_source_path(project: str,data_source: str,) -> str: - """Returns a fully-qualified data_source string.""" - return "projects/{project}/dataSources/{data_source}".format(project=project, data_source=data_source, ) - - @staticmethod - def parse_data_source_path(path: str) -> Dict[str,str]: - """Parses a data_source path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dataSources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def run_path(project: str,transfer_config: str,run: str,) -> str: - """Returns a fully-qualified run string.""" - return "projects/{project}/transferConfigs/{transfer_config}/runs/{run}".format(project=project, transfer_config=transfer_config, run=run, ) - - @staticmethod - def parse_run_path(path: str) -> Dict[str,str]: - """Parses a run path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/transferConfigs/(?P.+?)/runs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transfer_config_path(project: str,transfer_config: str,) -> str: - """Returns a fully-qualified transfer_config string.""" - return "projects/{project}/transferConfigs/{transfer_config}".format(project=project, transfer_config=transfer_config, ) - - @staticmethod - def parse_transfer_config_path(path: str) -> Dict[str,str]: - """Parses a transfer_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/transferConfigs/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DataTransferServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data 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 (Union[str, DataTransferServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DataTransferServiceTransport): - # transport is a DataTransferServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def get_data_source(self, - request: datatransfer.GetDataSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.DataSource: - r"""Retrieves a supported data source and returns its - settings, which can be used for UI rendering. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.GetDataSourceRequest): - The request object. A request to get data source info. - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/dataSources/{data_source_id}`` - or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.DataSource: - Represents data source metadata. - Metadata is sufficient to render UI and - request proper OAuth tokens. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.GetDataSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.GetDataSourceRequest): - request = datatransfer.GetDataSourceRequest(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_data_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_data_sources(self, - request: datatransfer.ListDataSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataSourcesPager: - r"""Lists supported data sources and returns their - settings, which can be used for UI rendering. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesRequest): - The request object. Request to list supported data - sources and their data transfer settings. - parent (str): - Required. The BigQuery project id for which data sources - should be returned. Must be in the form: - ``projects/{project_id}`` or - \`projects/{project_id}/locations/{location_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListDataSourcesPager: - Returns list of supported data - sources and their metadata. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.ListDataSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.ListDataSourcesRequest): - request = datatransfer.ListDataSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_data_sources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDataSourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_transfer_config(self, - request: datatransfer.CreateTransferConfigRequest = None, - *, - parent: str = None, - transfer_config: transfer.TransferConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Creates a new data transfer configuration. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.CreateTransferConfigRequest): - The request object. A request to create a data transfer - configuration. If new credentials are needed for this - transfer configuration, an authorization code must be - provided. If an authorization code is provided, the - transfer configuration will be associated with the user - id corresponding to the authorization code. Otherwise, - the transfer configuration will be associated with the - calling user. - parent (str): - Required. The BigQuery project id where the transfer - configuration should be created. Must be in the format - projects/{project_id}/locations/{location_id} or - projects/{project_id}. If specified location and - location of the destination bigquery dataset do not - match - the request will fail. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): - Required. Data transfer configuration - to create. - - This corresponds to the ``transfer_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transfer_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.CreateTransferConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.CreateTransferConfigRequest): - request = datatransfer.CreateTransferConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transfer_config is not None: - request.transfer_config = transfer_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_transfer_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_transfer_config(self, - request: datatransfer.UpdateTransferConfigRequest = None, - *, - transfer_config: transfer.TransferConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Updates a data transfer configuration. - All fields must be set, even if they are not updated. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.UpdateTransferConfigRequest): - The request object. A request to update a transfer - configuration. To update the user id of the transfer - configuration, an authorization code needs to be - provided. - transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): - Required. Data transfer configuration - to create. - - This corresponds to the ``transfer_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Required list of fields to - be updated in this request. - - 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.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transfer_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.UpdateTransferConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.UpdateTransferConfigRequest): - request = datatransfer.UpdateTransferConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transfer_config is not None: - request.transfer_config = transfer_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_transfer_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transfer_config.name", request.transfer_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_transfer_config(self, - request: datatransfer.DeleteTransferConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a data transfer configuration, - including any associated transfer runs and logs. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.DeleteTransferConfigRequest): - The request object. A request to delete data transfer - information. All associated transfer runs and log - messages will be deleted as well. - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.DeleteTransferConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.DeleteTransferConfigRequest): - request = datatransfer.DeleteTransferConfigRequest(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_transfer_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_transfer_config(self, - request: datatransfer.GetTransferConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferConfig: - r"""Returns information about a data transfer config. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.GetTransferConfigRequest): - The request object. A request to get data transfer - information. - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferConfig: - Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data - transfer. For example, destination_dataset_id - specifies where data should be stored. When a new - transfer configuration is created, the specified - destination_dataset_id is created when needed and - shared with the appropriate data source service - account. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.GetTransferConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.GetTransferConfigRequest): - request = datatransfer.GetTransferConfigRequest(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_transfer_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_transfer_configs(self, - request: datatransfer.ListTransferConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferConfigsPager: - r"""Returns information about all transfer configs owned - by a project in the specified location. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): - The request object. A request to list data transfers - configured for a BigQuery project. - parent (str): - Required. The BigQuery project id for which data sources - should be returned: ``projects/{project_id}`` or - ``projects/{project_id}/locations/{location_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferConfigsPager: - The returned list of pipelines in the - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.ListTransferConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.ListTransferConfigsRequest): - request = datatransfer.ListTransferConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_transfer_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTransferConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def schedule_transfer_runs(self, - request: datatransfer.ScheduleTransferRunsRequest = None, - *, - parent: str = None, - start_time: timestamp_pb2.Timestamp = None, - end_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.ScheduleTransferRunsResponse: - r"""Creates transfer runs for a time range [start_time, end_time]. - For each date - or whatever granularity the data source supports - - in the range, one transfer run is created. Note that runs are - created per UTC time in the time range. DEPRECATED: use - StartManualTransferRuns instead. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsRequest): - The request object. A request to schedule transfer runs - for a time range. - parent (str): - Required. Transfer configuration name in the form: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Start time of the range of transfer runs. For - example, ``"2017-05-25T00:00:00+00:00"``. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. End time of the range of transfer runs. For - example, ``"2017-05-30T00:00:00+00:00"``. - - This corresponds to the ``end_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse: - A response to schedule transfer runs - for a time range. - - """ - warnings.warn("DataTransferServiceClient.schedule_transfer_runs is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, start_time, end_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.ScheduleTransferRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.ScheduleTransferRunsRequest): - request = datatransfer.ScheduleTransferRunsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if start_time is not None: - request.start_time = start_time - if end_time is not None: - request.end_time = end_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.schedule_transfer_runs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def start_manual_transfer_runs(self, - request: datatransfer.StartManualTransferRunsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.StartManualTransferRunsResponse: - r"""Start manual transfer runs to be executed now with schedule_time - equal to current time. The transfer runs can be created for a - time range where the run_time is between start_time (inclusive) - and end_time (exclusive), or for a specific run_time. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest): - The request object. A request to start manual transfer - runs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.bigquery_datatransfer_v1.types.StartManualTransferRunsResponse: - A response to start manual transfer - runs. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.StartManualTransferRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.StartManualTransferRunsRequest): - request = datatransfer.StartManualTransferRunsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.start_manual_transfer_runs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_transfer_run(self, - request: datatransfer.GetTransferRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transfer.TransferRun: - r"""Returns information about the particular transfer - run. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.GetTransferRunRequest): - The request object. A request to get data transfer run - information. - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.TransferRun: - Represents a data transfer run. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.GetTransferRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.GetTransferRunRequest): - request = datatransfer.GetTransferRunRequest(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_transfer_run] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_transfer_run(self, - request: datatransfer.DeleteTransferRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified transfer run. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.DeleteTransferRunRequest): - The request object. A request to delete data transfer - run information. - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.DeleteTransferRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.DeleteTransferRunRequest): - request = datatransfer.DeleteTransferRunRequest(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_transfer_run] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_transfer_runs(self, - request: datatransfer.ListTransferRunsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferRunsPager: - r"""Returns information about running and completed jobs. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest): - The request object. A request to list data transfer - runs. UI can use this method to show/filter specific - data transfer runs. The data source can use this method - to request all scheduled transfer runs. - parent (str): - Required. Name of transfer configuration for which - transfer runs should be retrieved. Format of transfer - configuration resource name is: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferRunsPager: - The returned list of pipelines in the - project. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.ListTransferRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.ListTransferRunsRequest): - request = datatransfer.ListTransferRunsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_transfer_runs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTransferRunsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_transfer_logs(self, - request: datatransfer.ListTransferLogsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransferLogsPager: - r"""Returns user facing log messages for the data - transfer run. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsRequest): - The request object. A request to get user facing log - messages associated with data transfer run. - parent (str): - Required. Transfer run name in the form: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.pagers.ListTransferLogsPager: - The returned list transfer run - messages. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.ListTransferLogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.ListTransferLogsRequest): - request = datatransfer.ListTransferLogsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_transfer_logs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListTransferLogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def check_valid_creds(self, - request: datatransfer.CheckValidCredsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datatransfer.CheckValidCredsResponse: - r"""Returns true if valid credentials exist for the given - data source and requesting user. - Some data sources doesn't support service account, so we - need to talk to them on behalf of the end user. This API - just checks whether we have OAuth token for the - particular user, which is a pre-requisite before user - can create a transfer config. - - Args: - request (google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsRequest): - The request object. A request to determine whether the - user has valid credentials. This method is used to limit - the number of OAuth popups in the user interface. The - user id is inferred from the API call context. - If the data source has the Google+ authorization type, - this method returns false, as it cannot be determined - whether the credentials are already valid merely based - on the user id. - name (str): - Required. The data source in the form: - ``projects/{project_id}/dataSources/{data_source_id}`` - or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsResponse: - A response indicating whether the - credentials exist and are valid. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datatransfer.CheckValidCredsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datatransfer.CheckValidCredsRequest): - request = datatransfer.CheckValidCredsRequest(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.check_valid_creds] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-bigquery-datatransfer", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataTransferServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py deleted file mode 100644 index 77d00714..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/pagers.py +++ /dev/null @@ -1,507 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer - - -class ListDataSourcesPager: - """A pager for iterating through ``list_data_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``data_sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDataSources`` requests and continue to iterate - through the ``data_sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` - 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[..., datatransfer.ListDataSourcesResponse], - request: datatransfer.ListDataSourcesRequest, - response: datatransfer.ListDataSourcesResponse, - *, - 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.bigquery_datatransfer_v1.types.ListDataSourcesRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListDataSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[datatransfer.ListDataSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[datatransfer.DataSource]: - for page in self.pages: - yield from page.data_sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDataSourcesAsyncPager: - """A pager for iterating through ``list_data_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``data_sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDataSources`` requests and continue to iterate - through the ``data_sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse` - 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[datatransfer.ListDataSourcesResponse]], - request: datatransfer.ListDataSourcesRequest, - response: datatransfer.ListDataSourcesResponse, - *, - 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.bigquery_datatransfer_v1.types.ListDataSourcesRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListDataSourcesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListDataSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[datatransfer.ListDataSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[datatransfer.DataSource]: - async def async_generator(): - async for page in self.pages: - for response in page.data_sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferConfigsPager: - """A pager for iterating through ``list_transfer_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``transfer_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTransferConfigs`` requests and continue to iterate - through the ``transfer_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` - 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[..., datatransfer.ListTransferConfigsResponse], - request: datatransfer.ListTransferConfigsRequest, - response: datatransfer.ListTransferConfigsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[datatransfer.ListTransferConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[transfer.TransferConfig]: - for page in self.pages: - yield from page.transfer_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferConfigsAsyncPager: - """A pager for iterating through ``list_transfer_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``transfer_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTransferConfigs`` requests and continue to iterate - through the ``transfer_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse` - 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[datatransfer.ListTransferConfigsResponse]], - request: datatransfer.ListTransferConfigsRequest, - response: datatransfer.ListTransferConfigsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferConfigsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferConfigsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[datatransfer.ListTransferConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[transfer.TransferConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.transfer_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferRunsPager: - """A pager for iterating through ``list_transfer_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``transfer_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTransferRuns`` requests and continue to iterate - through the ``transfer_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` - 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[..., datatransfer.ListTransferRunsResponse], - request: datatransfer.ListTransferRunsRequest, - response: datatransfer.ListTransferRunsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferRunsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[datatransfer.ListTransferRunsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[transfer.TransferRun]: - for page in self.pages: - yield from page.transfer_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferRunsAsyncPager: - """A pager for iterating through ``list_transfer_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``transfer_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTransferRuns`` requests and continue to iterate - through the ``transfer_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse` - 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[datatransfer.ListTransferRunsResponse]], - request: datatransfer.ListTransferRunsRequest, - response: datatransfer.ListTransferRunsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferRunsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[datatransfer.ListTransferRunsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[transfer.TransferRun]: - async def async_generator(): - async for page in self.pages: - for response in page.transfer_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferLogsPager: - """A pager for iterating through ``list_transfer_logs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``transfer_messages`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTransferLogs`` requests and continue to iterate - through the ``transfer_messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` - 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[..., datatransfer.ListTransferLogsResponse], - request: datatransfer.ListTransferLogsRequest, - response: datatransfer.ListTransferLogsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferLogsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferLogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[datatransfer.ListTransferLogsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[transfer.TransferMessage]: - for page in self.pages: - yield from page.transfer_messages - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransferLogsAsyncPager: - """A pager for iterating through ``list_transfer_logs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``transfer_messages`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTransferLogs`` requests and continue to iterate - through the ``transfer_messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse` - 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[datatransfer.ListTransferLogsResponse]], - request: datatransfer.ListTransferLogsRequest, - response: datatransfer.ListTransferLogsResponse, - *, - 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.bigquery_datatransfer_v1.types.ListTransferLogsRequest): - The initial request object. - response (google.cloud.bigquery_datatransfer_v1.types.ListTransferLogsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = datatransfer.ListTransferLogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[datatransfer.ListTransferLogsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[transfer.TransferMessage]: - async def async_generator(): - async for page in self.pages: - for response in page.transfer_messages: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py deleted file mode 100644 index 0607aff0..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 DataTransferServiceTransport -from .grpc import DataTransferServiceGrpcTransport -from .grpc_asyncio import DataTransferServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DataTransferServiceTransport]] -_transport_registry['grpc'] = DataTransferServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DataTransferServiceGrpcAsyncIOTransport - -__all__ = ( - 'DataTransferServiceTransport', - 'DataTransferServiceGrpcTransport', - 'DataTransferServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py deleted file mode 100644 index 17fa2de7..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/base.py +++ /dev/null @@ -1,422 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-bigquery-datatransfer', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class DataTransferServiceTransport(abc.ABC): - """Abstract transport class for DataTransferService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'bigquerydatatransfer.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: 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, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_data_source: gapic_v1.method.wrap_method( - self.get_data_source, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.list_data_sources: gapic_v1.method.wrap_method( - self.list_data_sources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.create_transfer_config: gapic_v1.method.wrap_method( - self.create_transfer_config, - default_timeout=30.0, - client_info=client_info, - ), - self.update_transfer_config: gapic_v1.method.wrap_method( - self.update_transfer_config, - default_timeout=30.0, - client_info=client_info, - ), - self.delete_transfer_config: gapic_v1.method.wrap_method( - self.delete_transfer_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.get_transfer_config: gapic_v1.method.wrap_method( - self.get_transfer_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.list_transfer_configs: gapic_v1.method.wrap_method( - self.list_transfer_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.schedule_transfer_runs: gapic_v1.method.wrap_method( - self.schedule_transfer_runs, - default_timeout=30.0, - client_info=client_info, - ), - self.start_manual_transfer_runs: gapic_v1.method.wrap_method( - self.start_manual_transfer_runs, - default_timeout=None, - client_info=client_info, - ), - self.get_transfer_run: gapic_v1.method.wrap_method( - self.get_transfer_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.delete_transfer_run: gapic_v1.method.wrap_method( - self.delete_transfer_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.list_transfer_runs: gapic_v1.method.wrap_method( - self.list_transfer_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.list_transfer_logs: gapic_v1.method.wrap_method( - self.list_transfer_logs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - self.check_valid_creds: gapic_v1.method.wrap_method( - self.check_valid_creds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=20.0, - ), - default_timeout=20.0, - client_info=client_info, - ), - } - - @property - def get_data_source(self) -> Callable[ - [datatransfer.GetDataSourceRequest], - Union[ - datatransfer.DataSource, - Awaitable[datatransfer.DataSource] - ]]: - raise NotImplementedError() - - @property - def list_data_sources(self) -> Callable[ - [datatransfer.ListDataSourcesRequest], - Union[ - datatransfer.ListDataSourcesResponse, - Awaitable[datatransfer.ListDataSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def create_transfer_config(self) -> Callable[ - [datatransfer.CreateTransferConfigRequest], - Union[ - transfer.TransferConfig, - Awaitable[transfer.TransferConfig] - ]]: - raise NotImplementedError() - - @property - def update_transfer_config(self) -> Callable[ - [datatransfer.UpdateTransferConfigRequest], - Union[ - transfer.TransferConfig, - Awaitable[transfer.TransferConfig] - ]]: - raise NotImplementedError() - - @property - def delete_transfer_config(self) -> Callable[ - [datatransfer.DeleteTransferConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_transfer_config(self) -> Callable[ - [datatransfer.GetTransferConfigRequest], - Union[ - transfer.TransferConfig, - Awaitable[transfer.TransferConfig] - ]]: - raise NotImplementedError() - - @property - def list_transfer_configs(self) -> Callable[ - [datatransfer.ListTransferConfigsRequest], - Union[ - datatransfer.ListTransferConfigsResponse, - Awaitable[datatransfer.ListTransferConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def schedule_transfer_runs(self) -> Callable[ - [datatransfer.ScheduleTransferRunsRequest], - Union[ - datatransfer.ScheduleTransferRunsResponse, - Awaitable[datatransfer.ScheduleTransferRunsResponse] - ]]: - raise NotImplementedError() - - @property - def start_manual_transfer_runs(self) -> Callable[ - [datatransfer.StartManualTransferRunsRequest], - Union[ - datatransfer.StartManualTransferRunsResponse, - Awaitable[datatransfer.StartManualTransferRunsResponse] - ]]: - raise NotImplementedError() - - @property - def get_transfer_run(self) -> Callable[ - [datatransfer.GetTransferRunRequest], - Union[ - transfer.TransferRun, - Awaitable[transfer.TransferRun] - ]]: - raise NotImplementedError() - - @property - def delete_transfer_run(self) -> Callable[ - [datatransfer.DeleteTransferRunRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_transfer_runs(self) -> Callable[ - [datatransfer.ListTransferRunsRequest], - Union[ - datatransfer.ListTransferRunsResponse, - Awaitable[datatransfer.ListTransferRunsResponse] - ]]: - raise NotImplementedError() - - @property - def list_transfer_logs(self) -> Callable[ - [datatransfer.ListTransferLogsRequest], - Union[ - datatransfer.ListTransferLogsResponse, - Awaitable[datatransfer.ListTransferLogsResponse] - ]]: - raise NotImplementedError() - - @property - def check_valid_creds(self) -> Callable[ - [datatransfer.CheckValidCredsRequest], - Union[ - datatransfer.CheckValidCredsResponse, - Awaitable[datatransfer.CheckValidCredsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DataTransferServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py deleted file mode 100644 index 60486c31..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc.py +++ /dev/null @@ -1,615 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import empty_pb2 # type: ignore -from .base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO - - -class DataTransferServiceGrpcTransport(DataTransferServiceTransport): - """gRPC backend transport for DataTransferService. - - The Google BigQuery Data Transfer Service API enables - BigQuery users to configure the transfer of their data from - other Google Products into BigQuery. This service contains - methods that are end user exposed. It backs up the frontend. - - 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 = 'bigquerydatatransfer.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin 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 grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'bigquerydatatransfer.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: 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 get_data_source(self) -> Callable[ - [datatransfer.GetDataSourceRequest], - datatransfer.DataSource]: - r"""Return a callable for the get data source method over gRPC. - - Retrieves a supported data source and returns its - settings, which can be used for UI rendering. - - Returns: - Callable[[~.GetDataSourceRequest], - ~.DataSource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['get_data_source'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetDataSource', - request_serializer=datatransfer.GetDataSourceRequest.serialize, - response_deserializer=datatransfer.DataSource.deserialize, - ) - return self._stubs['get_data_source'] - - @property - def list_data_sources(self) -> Callable[ - [datatransfer.ListDataSourcesRequest], - datatransfer.ListDataSourcesResponse]: - r"""Return a callable for the list data sources method over gRPC. - - Lists supported data sources and returns their - settings, which can be used for UI rendering. - - Returns: - Callable[[~.ListDataSourcesRequest], - ~.ListDataSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_sources' not in self._stubs: - self._stubs['list_data_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListDataSources', - request_serializer=datatransfer.ListDataSourcesRequest.serialize, - response_deserializer=datatransfer.ListDataSourcesResponse.deserialize, - ) - return self._stubs['list_data_sources'] - - @property - def create_transfer_config(self) -> Callable[ - [datatransfer.CreateTransferConfigRequest], - transfer.TransferConfig]: - r"""Return a callable for the create transfer config method over gRPC. - - Creates a new data transfer configuration. - - Returns: - Callable[[~.CreateTransferConfigRequest], - ~.TransferConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CreateTransferConfig', - request_serializer=datatransfer.CreateTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['create_transfer_config'] - - @property - def update_transfer_config(self) -> Callable[ - [datatransfer.UpdateTransferConfigRequest], - transfer.TransferConfig]: - r"""Return a callable for the update transfer config method over gRPC. - - Updates a data transfer configuration. - All fields must be set, even if they are not updated. - - Returns: - Callable[[~.UpdateTransferConfigRequest], - ~.TransferConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/UpdateTransferConfig', - request_serializer=datatransfer.UpdateTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['update_transfer_config'] - - @property - def delete_transfer_config(self) -> Callable[ - [datatransfer.DeleteTransferConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete transfer config method over gRPC. - - Deletes a data transfer configuration, - including any associated transfer runs and logs. - - Returns: - Callable[[~.DeleteTransferConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferConfig', - request_serializer=datatransfer.DeleteTransferConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transfer_config'] - - @property - def get_transfer_config(self) -> Callable[ - [datatransfer.GetTransferConfigRequest], - transfer.TransferConfig]: - r"""Return a callable for the get transfer config method over gRPC. - - Returns information about a data transfer config. - - Returns: - Callable[[~.GetTransferConfigRequest], - ~.TransferConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['get_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferConfig', - request_serializer=datatransfer.GetTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['get_transfer_config'] - - @property - def list_transfer_configs(self) -> Callable[ - [datatransfer.ListTransferConfigsRequest], - datatransfer.ListTransferConfigsResponse]: - r"""Return a callable for the list transfer configs method over gRPC. - - Returns information about all transfer configs owned - by a project in the specified location. - - Returns: - Callable[[~.ListTransferConfigsRequest], - ~.ListTransferConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_configs' not in self._stubs: - self._stubs['list_transfer_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferConfigs', - request_serializer=datatransfer.ListTransferConfigsRequest.serialize, - response_deserializer=datatransfer.ListTransferConfigsResponse.deserialize, - ) - return self._stubs['list_transfer_configs'] - - @property - def schedule_transfer_runs(self) -> Callable[ - [datatransfer.ScheduleTransferRunsRequest], - datatransfer.ScheduleTransferRunsResponse]: - r"""Return a callable for the schedule transfer runs method over gRPC. - - Creates transfer runs for a time range [start_time, end_time]. - For each date - or whatever granularity the data source supports - - in the range, one transfer run is created. Note that runs are - created per UTC time in the time range. DEPRECATED: use - StartManualTransferRuns instead. - - Returns: - Callable[[~.ScheduleTransferRunsRequest], - ~.ScheduleTransferRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'schedule_transfer_runs' not in self._stubs: - self._stubs['schedule_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ScheduleTransferRuns', - request_serializer=datatransfer.ScheduleTransferRunsRequest.serialize, - response_deserializer=datatransfer.ScheduleTransferRunsResponse.deserialize, - ) - return self._stubs['schedule_transfer_runs'] - - @property - def start_manual_transfer_runs(self) -> Callable[ - [datatransfer.StartManualTransferRunsRequest], - datatransfer.StartManualTransferRunsResponse]: - r"""Return a callable for the start manual transfer runs method over gRPC. - - Start manual transfer runs to be executed now with schedule_time - equal to current time. The transfer runs can be created for a - time range where the run_time is between start_time (inclusive) - and end_time (exclusive), or for a specific run_time. - - Returns: - Callable[[~.StartManualTransferRunsRequest], - ~.StartManualTransferRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_manual_transfer_runs' not in self._stubs: - self._stubs['start_manual_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/StartManualTransferRuns', - request_serializer=datatransfer.StartManualTransferRunsRequest.serialize, - response_deserializer=datatransfer.StartManualTransferRunsResponse.deserialize, - ) - return self._stubs['start_manual_transfer_runs'] - - @property - def get_transfer_run(self) -> Callable[ - [datatransfer.GetTransferRunRequest], - transfer.TransferRun]: - r"""Return a callable for the get transfer run method over gRPC. - - Returns information about the particular transfer - run. - - Returns: - Callable[[~.GetTransferRunRequest], - ~.TransferRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_run' not in self._stubs: - self._stubs['get_transfer_run'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferRun', - request_serializer=datatransfer.GetTransferRunRequest.serialize, - response_deserializer=transfer.TransferRun.deserialize, - ) - return self._stubs['get_transfer_run'] - - @property - def delete_transfer_run(self) -> Callable[ - [datatransfer.DeleteTransferRunRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete transfer run method over gRPC. - - Deletes the specified transfer run. - - Returns: - Callable[[~.DeleteTransferRunRequest], - ~.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_run' not in self._stubs: - self._stubs['delete_transfer_run'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferRun', - request_serializer=datatransfer.DeleteTransferRunRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transfer_run'] - - @property - def list_transfer_runs(self) -> Callable[ - [datatransfer.ListTransferRunsRequest], - datatransfer.ListTransferRunsResponse]: - r"""Return a callable for the list transfer runs method over gRPC. - - Returns information about running and completed jobs. - - Returns: - Callable[[~.ListTransferRunsRequest], - ~.ListTransferRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_runs' not in self._stubs: - self._stubs['list_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferRuns', - request_serializer=datatransfer.ListTransferRunsRequest.serialize, - response_deserializer=datatransfer.ListTransferRunsResponse.deserialize, - ) - return self._stubs['list_transfer_runs'] - - @property - def list_transfer_logs(self) -> Callable[ - [datatransfer.ListTransferLogsRequest], - datatransfer.ListTransferLogsResponse]: - r"""Return a callable for the list transfer logs method over gRPC. - - Returns user facing log messages for the data - transfer run. - - Returns: - Callable[[~.ListTransferLogsRequest], - ~.ListTransferLogsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_logs' not in self._stubs: - self._stubs['list_transfer_logs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferLogs', - request_serializer=datatransfer.ListTransferLogsRequest.serialize, - response_deserializer=datatransfer.ListTransferLogsResponse.deserialize, - ) - return self._stubs['list_transfer_logs'] - - @property - def check_valid_creds(self) -> Callable[ - [datatransfer.CheckValidCredsRequest], - datatransfer.CheckValidCredsResponse]: - r"""Return a callable for the check valid creds method over gRPC. - - Returns true if valid credentials exist for the given - data source and requesting user. - Some data sources doesn't support service account, so we - need to talk to them on behalf of the end user. This API - just checks whether we have OAuth token for the - particular user, which is a pre-requisite before user - can create a transfer config. - - Returns: - Callable[[~.CheckValidCredsRequest], - ~.CheckValidCredsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'check_valid_creds' not in self._stubs: - self._stubs['check_valid_creds'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CheckValidCreds', - request_serializer=datatransfer.CheckValidCredsRequest.serialize, - response_deserializer=datatransfer.CheckValidCredsResponse.deserialize, - ) - return self._stubs['check_valid_creds'] - - -__all__ = ( - 'DataTransferServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py deleted file mode 100644 index 74b122ce..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,619 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import empty_pb2 # type: ignore -from .base import DataTransferServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DataTransferServiceGrpcTransport - - -class DataTransferServiceGrpcAsyncIOTransport(DataTransferServiceTransport): - """gRPC AsyncIO backend transport for DataTransferService. - - The Google BigQuery Data Transfer Service API enables - BigQuery users to configure the transfer of their data from - other Google Products into BigQuery. This service contains - methods that are end user exposed. It backs up the frontend. - - 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 = 'bigquerydatatransfer.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'bigquerydatatransfer.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin 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 grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 get_data_source(self) -> Callable[ - [datatransfer.GetDataSourceRequest], - Awaitable[datatransfer.DataSource]]: - r"""Return a callable for the get data source method over gRPC. - - Retrieves a supported data source and returns its - settings, which can be used for UI rendering. - - Returns: - Callable[[~.GetDataSourceRequest], - Awaitable[~.DataSource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_source' not in self._stubs: - self._stubs['get_data_source'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetDataSource', - request_serializer=datatransfer.GetDataSourceRequest.serialize, - response_deserializer=datatransfer.DataSource.deserialize, - ) - return self._stubs['get_data_source'] - - @property - def list_data_sources(self) -> Callable[ - [datatransfer.ListDataSourcesRequest], - Awaitable[datatransfer.ListDataSourcesResponse]]: - r"""Return a callable for the list data sources method over gRPC. - - Lists supported data sources and returns their - settings, which can be used for UI rendering. - - Returns: - Callable[[~.ListDataSourcesRequest], - Awaitable[~.ListDataSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_data_sources' not in self._stubs: - self._stubs['list_data_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListDataSources', - request_serializer=datatransfer.ListDataSourcesRequest.serialize, - response_deserializer=datatransfer.ListDataSourcesResponse.deserialize, - ) - return self._stubs['list_data_sources'] - - @property - def create_transfer_config(self) -> Callable[ - [datatransfer.CreateTransferConfigRequest], - Awaitable[transfer.TransferConfig]]: - r"""Return a callable for the create transfer config method over gRPC. - - Creates a new data transfer configuration. - - Returns: - Callable[[~.CreateTransferConfigRequest], - Awaitable[~.TransferConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CreateTransferConfig', - request_serializer=datatransfer.CreateTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['create_transfer_config'] - - @property - def update_transfer_config(self) -> Callable[ - [datatransfer.UpdateTransferConfigRequest], - Awaitable[transfer.TransferConfig]]: - r"""Return a callable for the update transfer config method over gRPC. - - Updates a data transfer configuration. - All fields must be set, even if they are not updated. - - Returns: - Callable[[~.UpdateTransferConfigRequest], - Awaitable[~.TransferConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/UpdateTransferConfig', - request_serializer=datatransfer.UpdateTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['update_transfer_config'] - - @property - def delete_transfer_config(self) -> Callable[ - [datatransfer.DeleteTransferConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete transfer config method over gRPC. - - Deletes a data transfer configuration, - including any associated transfer runs and logs. - - Returns: - Callable[[~.DeleteTransferConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferConfig', - request_serializer=datatransfer.DeleteTransferConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transfer_config'] - - @property - def get_transfer_config(self) -> Callable[ - [datatransfer.GetTransferConfigRequest], - Awaitable[transfer.TransferConfig]]: - r"""Return a callable for the get transfer config method over gRPC. - - Returns information about a data transfer config. - - Returns: - Callable[[~.GetTransferConfigRequest], - Awaitable[~.TransferConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['get_transfer_config'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferConfig', - request_serializer=datatransfer.GetTransferConfigRequest.serialize, - response_deserializer=transfer.TransferConfig.deserialize, - ) - return self._stubs['get_transfer_config'] - - @property - def list_transfer_configs(self) -> Callable[ - [datatransfer.ListTransferConfigsRequest], - Awaitable[datatransfer.ListTransferConfigsResponse]]: - r"""Return a callable for the list transfer configs method over gRPC. - - Returns information about all transfer configs owned - by a project in the specified location. - - Returns: - Callable[[~.ListTransferConfigsRequest], - Awaitable[~.ListTransferConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_configs' not in self._stubs: - self._stubs['list_transfer_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferConfigs', - request_serializer=datatransfer.ListTransferConfigsRequest.serialize, - response_deserializer=datatransfer.ListTransferConfigsResponse.deserialize, - ) - return self._stubs['list_transfer_configs'] - - @property - def schedule_transfer_runs(self) -> Callable[ - [datatransfer.ScheduleTransferRunsRequest], - Awaitable[datatransfer.ScheduleTransferRunsResponse]]: - r"""Return a callable for the schedule transfer runs method over gRPC. - - Creates transfer runs for a time range [start_time, end_time]. - For each date - or whatever granularity the data source supports - - in the range, one transfer run is created. Note that runs are - created per UTC time in the time range. DEPRECATED: use - StartManualTransferRuns instead. - - Returns: - Callable[[~.ScheduleTransferRunsRequest], - Awaitable[~.ScheduleTransferRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'schedule_transfer_runs' not in self._stubs: - self._stubs['schedule_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ScheduleTransferRuns', - request_serializer=datatransfer.ScheduleTransferRunsRequest.serialize, - response_deserializer=datatransfer.ScheduleTransferRunsResponse.deserialize, - ) - return self._stubs['schedule_transfer_runs'] - - @property - def start_manual_transfer_runs(self) -> Callable[ - [datatransfer.StartManualTransferRunsRequest], - Awaitable[datatransfer.StartManualTransferRunsResponse]]: - r"""Return a callable for the start manual transfer runs method over gRPC. - - Start manual transfer runs to be executed now with schedule_time - equal to current time. The transfer runs can be created for a - time range where the run_time is between start_time (inclusive) - and end_time (exclusive), or for a specific run_time. - - Returns: - Callable[[~.StartManualTransferRunsRequest], - Awaitable[~.StartManualTransferRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_manual_transfer_runs' not in self._stubs: - self._stubs['start_manual_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/StartManualTransferRuns', - request_serializer=datatransfer.StartManualTransferRunsRequest.serialize, - response_deserializer=datatransfer.StartManualTransferRunsResponse.deserialize, - ) - return self._stubs['start_manual_transfer_runs'] - - @property - def get_transfer_run(self) -> Callable[ - [datatransfer.GetTransferRunRequest], - Awaitable[transfer.TransferRun]]: - r"""Return a callable for the get transfer run method over gRPC. - - Returns information about the particular transfer - run. - - Returns: - Callable[[~.GetTransferRunRequest], - Awaitable[~.TransferRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_run' not in self._stubs: - self._stubs['get_transfer_run'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/GetTransferRun', - request_serializer=datatransfer.GetTransferRunRequest.serialize, - response_deserializer=transfer.TransferRun.deserialize, - ) - return self._stubs['get_transfer_run'] - - @property - def delete_transfer_run(self) -> Callable[ - [datatransfer.DeleteTransferRunRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete transfer run method over gRPC. - - Deletes the specified transfer run. - - Returns: - Callable[[~.DeleteTransferRunRequest], - 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_run' not in self._stubs: - self._stubs['delete_transfer_run'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/DeleteTransferRun', - request_serializer=datatransfer.DeleteTransferRunRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transfer_run'] - - @property - def list_transfer_runs(self) -> Callable[ - [datatransfer.ListTransferRunsRequest], - Awaitable[datatransfer.ListTransferRunsResponse]]: - r"""Return a callable for the list transfer runs method over gRPC. - - Returns information about running and completed jobs. - - Returns: - Callable[[~.ListTransferRunsRequest], - Awaitable[~.ListTransferRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_runs' not in self._stubs: - self._stubs['list_transfer_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferRuns', - request_serializer=datatransfer.ListTransferRunsRequest.serialize, - response_deserializer=datatransfer.ListTransferRunsResponse.deserialize, - ) - return self._stubs['list_transfer_runs'] - - @property - def list_transfer_logs(self) -> Callable[ - [datatransfer.ListTransferLogsRequest], - Awaitable[datatransfer.ListTransferLogsResponse]]: - r"""Return a callable for the list transfer logs method over gRPC. - - Returns user facing log messages for the data - transfer run. - - Returns: - Callable[[~.ListTransferLogsRequest], - Awaitable[~.ListTransferLogsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_logs' not in self._stubs: - self._stubs['list_transfer_logs'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/ListTransferLogs', - request_serializer=datatransfer.ListTransferLogsRequest.serialize, - response_deserializer=datatransfer.ListTransferLogsResponse.deserialize, - ) - return self._stubs['list_transfer_logs'] - - @property - def check_valid_creds(self) -> Callable[ - [datatransfer.CheckValidCredsRequest], - Awaitable[datatransfer.CheckValidCredsResponse]]: - r"""Return a callable for the check valid creds method over gRPC. - - Returns true if valid credentials exist for the given - data source and requesting user. - Some data sources doesn't support service account, so we - need to talk to them on behalf of the end user. This API - just checks whether we have OAuth token for the - particular user, which is a pre-requisite before user - can create a transfer config. - - Returns: - Callable[[~.CheckValidCredsRequest], - Awaitable[~.CheckValidCredsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'check_valid_creds' not in self._stubs: - self._stubs['check_valid_creds'] = self.grpc_channel.unary_unary( - '/google.cloud.bigquery.datatransfer.v1.DataTransferService/CheckValidCreds', - request_serializer=datatransfer.CheckValidCredsRequest.serialize, - response_deserializer=datatransfer.CheckValidCredsResponse.deserialize, - ) - return self._stubs['check_valid_creds'] - - -__all__ = ( - 'DataTransferServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py deleted file mode 100644 index 2e87af4c..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/__init__.py +++ /dev/null @@ -1,82 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .datatransfer import ( - CheckValidCredsRequest, - CheckValidCredsResponse, - CreateTransferConfigRequest, - DataSource, - DataSourceParameter, - DeleteTransferConfigRequest, - DeleteTransferRunRequest, - GetDataSourceRequest, - GetTransferConfigRequest, - GetTransferRunRequest, - ListDataSourcesRequest, - ListDataSourcesResponse, - ListTransferConfigsRequest, - ListTransferConfigsResponse, - ListTransferLogsRequest, - ListTransferLogsResponse, - ListTransferRunsRequest, - ListTransferRunsResponse, - ScheduleTransferRunsRequest, - ScheduleTransferRunsResponse, - StartManualTransferRunsRequest, - StartManualTransferRunsResponse, - UpdateTransferConfigRequest, -) -from .transfer import ( - EmailPreferences, - ScheduleOptions, - TransferConfig, - TransferMessage, - TransferRun, - TransferState, - TransferType, -) - -__all__ = ( - 'CheckValidCredsRequest', - 'CheckValidCredsResponse', - 'CreateTransferConfigRequest', - 'DataSource', - 'DataSourceParameter', - 'DeleteTransferConfigRequest', - 'DeleteTransferRunRequest', - 'GetDataSourceRequest', - 'GetTransferConfigRequest', - 'GetTransferRunRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'ListTransferConfigsRequest', - 'ListTransferConfigsResponse', - 'ListTransferLogsRequest', - 'ListTransferLogsResponse', - 'ListTransferRunsRequest', - 'ListTransferRunsResponse', - 'ScheduleTransferRunsRequest', - 'ScheduleTransferRunsResponse', - 'StartManualTransferRunsRequest', - 'StartManualTransferRunsResponse', - 'UpdateTransferConfigRequest', - 'EmailPreferences', - 'ScheduleOptions', - 'TransferConfig', - 'TransferMessage', - 'TransferRun', - 'TransferState', - 'TransferType', -) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py deleted file mode 100644 index 88203842..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/datatransfer.py +++ /dev/null @@ -1,1023 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.bigquery.datatransfer.v1', - manifest={ - 'DataSourceParameter', - 'DataSource', - 'GetDataSourceRequest', - 'ListDataSourcesRequest', - 'ListDataSourcesResponse', - 'CreateTransferConfigRequest', - 'UpdateTransferConfigRequest', - 'GetTransferConfigRequest', - 'DeleteTransferConfigRequest', - 'GetTransferRunRequest', - 'DeleteTransferRunRequest', - 'ListTransferConfigsRequest', - 'ListTransferConfigsResponse', - 'ListTransferRunsRequest', - 'ListTransferRunsResponse', - 'ListTransferLogsRequest', - 'ListTransferLogsResponse', - 'CheckValidCredsRequest', - 'CheckValidCredsResponse', - 'ScheduleTransferRunsRequest', - 'ScheduleTransferRunsResponse', - 'StartManualTransferRunsRequest', - 'StartManualTransferRunsResponse', - }, -) - - -class DataSourceParameter(proto.Message): - r"""Represents a data source parameter with validation rules, so - that parameters can be rendered in the UI. These parameters are - given to us by supported data sources, and include all needed - information for rendering and validation. - Thus, whoever uses this api can decide to generate either - generic ui, or custom data source specific forms. - - Attributes: - param_id (str): - Parameter identifier. - display_name (str): - Parameter display name in the user interface. - description (str): - Parameter description. - type_ (google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter.Type): - Parameter type. - required (bool): - Is parameter required. - repeated (bool): - Deprecated. This field has no effect. - validation_regex (str): - Regular expression which can be used for - parameter validation. - allowed_values (Sequence[str]): - All possible values for the parameter. - min_value (google.protobuf.wrappers_pb2.DoubleValue): - For integer and double values specifies - minimum allowed value. - max_value (google.protobuf.wrappers_pb2.DoubleValue): - For integer and double values specifies - maxminum allowed value. - fields (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter]): - Deprecated. This field has no effect. - validation_description (str): - Description of the requirements for this - field, in case the user input does not fulfill - the regex pattern or min/max values. - validation_help_url (str): - URL to a help document to further explain the - naming requirements. - immutable (bool): - Cannot be changed after initial creation. - recurse (bool): - Deprecated. This field has no effect. - deprecated (bool): - If true, it should not be used in new - transfers, and it should not be visible to - users. - """ - class Type(proto.Enum): - r"""Parameter type.""" - TYPE_UNSPECIFIED = 0 - STRING = 1 - INTEGER = 2 - DOUBLE = 3 - BOOLEAN = 4 - RECORD = 5 - PLUS_PAGE = 6 - - param_id = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - type_ = proto.Field( - proto.ENUM, - number=4, - enum=Type, - ) - required = proto.Field( - proto.BOOL, - number=5, - ) - repeated = proto.Field( - proto.BOOL, - number=6, - ) - validation_regex = proto.Field( - proto.STRING, - number=7, - ) - allowed_values = proto.RepeatedField( - proto.STRING, - number=8, - ) - min_value = proto.Field( - proto.MESSAGE, - number=9, - message=wrappers_pb2.DoubleValue, - ) - max_value = proto.Field( - proto.MESSAGE, - number=10, - message=wrappers_pb2.DoubleValue, - ) - fields = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='DataSourceParameter', - ) - validation_description = proto.Field( - proto.STRING, - number=12, - ) - validation_help_url = proto.Field( - proto.STRING, - number=13, - ) - immutable = proto.Field( - proto.BOOL, - number=14, - ) - recurse = proto.Field( - proto.BOOL, - number=15, - ) - deprecated = proto.Field( - proto.BOOL, - number=20, - ) - - -class DataSource(proto.Message): - r"""Represents data source metadata. Metadata is sufficient to - render UI and request proper OAuth tokens. - - Attributes: - name (str): - Output only. Data source resource name. - data_source_id (str): - Data source id. - display_name (str): - User friendly data source name. - description (str): - User friendly data source description string. - client_id (str): - Data source client id which should be used to - receive refresh token. - scopes (Sequence[str]): - Api auth scopes for which refresh token needs - to be obtained. These are scopes needed by a - data source to prepare data and ingest them into - BigQuery, e.g., - https://www.googleapis.com/auth/bigquery - transfer_type (google.cloud.bigquery_datatransfer_v1.types.TransferType): - Deprecated. This field has no effect. - supports_multiple_transfers (bool): - Deprecated. This field has no effect. - update_deadline_seconds (int): - The number of seconds to wait for an update - from the data source before the Data Transfer - Service marks the transfer as FAILED. - default_schedule (str): - Default data transfer schedule. Examples of valid schedules - include: ``1st,3rd monday of month 15:30``, - ``every wed,fri of jan,jun 13:15``, and - ``first sunday of quarter 00:00``. - supports_custom_schedule (bool): - Specifies whether the data source supports a user defined - schedule, or operates on the default schedule. When set to - ``true``, user can override default schedule. - parameters (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSourceParameter]): - Data source parameters. - help_url (str): - Url for the help document for this data - source. - authorization_type (google.cloud.bigquery_datatransfer_v1.types.DataSource.AuthorizationType): - Indicates the type of authorization. - data_refresh_type (google.cloud.bigquery_datatransfer_v1.types.DataSource.DataRefreshType): - Specifies whether the data source supports - automatic data refresh for the past few days, - and how it's supported. For some data sources, - data might not be complete until a few days - later, so it's useful to refresh data - automatically. - default_data_refresh_window_days (int): - Default data refresh window on days. Only meaningful when - ``data_refresh_type`` = ``SLIDING_WINDOW``. - manual_runs_disabled (bool): - Disables backfilling and manual run - scheduling for the data source. - minimum_schedule_interval (google.protobuf.duration_pb2.Duration): - The minimum interval for scheduler to - schedule runs. - """ - class AuthorizationType(proto.Enum): - r"""The type of authorization needed for this data source.""" - AUTHORIZATION_TYPE_UNSPECIFIED = 0 - AUTHORIZATION_CODE = 1 - GOOGLE_PLUS_AUTHORIZATION_CODE = 2 - FIRST_PARTY_OAUTH = 3 - - class DataRefreshType(proto.Enum): - r"""Represents how the data source supports data auto refresh.""" - DATA_REFRESH_TYPE_UNSPECIFIED = 0 - SLIDING_WINDOW = 1 - CUSTOM_SLIDING_WINDOW = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - data_source_id = proto.Field( - proto.STRING, - number=2, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - client_id = proto.Field( - proto.STRING, - number=5, - ) - scopes = proto.RepeatedField( - proto.STRING, - number=6, - ) - transfer_type = proto.Field( - proto.ENUM, - number=7, - enum=transfer.TransferType, - ) - supports_multiple_transfers = proto.Field( - proto.BOOL, - number=8, - ) - update_deadline_seconds = proto.Field( - proto.INT32, - number=9, - ) - default_schedule = proto.Field( - proto.STRING, - number=10, - ) - supports_custom_schedule = proto.Field( - proto.BOOL, - number=11, - ) - parameters = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='DataSourceParameter', - ) - help_url = proto.Field( - proto.STRING, - number=13, - ) - authorization_type = proto.Field( - proto.ENUM, - number=14, - enum=AuthorizationType, - ) - data_refresh_type = proto.Field( - proto.ENUM, - number=15, - enum=DataRefreshType, - ) - default_data_refresh_window_days = proto.Field( - proto.INT32, - number=16, - ) - manual_runs_disabled = proto.Field( - proto.BOOL, - number=17, - ) - minimum_schedule_interval = proto.Field( - proto.MESSAGE, - number=18, - message=duration_pb2.Duration, - ) - - -class GetDataSourceRequest(proto.Message): - r"""A request to get data source info. - Attributes: - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/dataSources/{data_source_id}`` or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDataSourcesRequest(proto.Message): - r"""Request to list supported data sources and their data - transfer settings. - - Attributes: - parent (str): - Required. The BigQuery project id for which data sources - should be returned. Must be in the form: - ``projects/{project_id}`` or - \`projects/{project_id}/locations/{location_id} - page_token (str): - Pagination token, which can be used to request a specific - page of ``ListDataSourcesRequest`` list results. For - multiple-page results, ``ListDataSourcesResponse`` outputs a - ``next_page`` token, which can be used as the ``page_token`` - value to request the next page of list results. - page_size (int): - Page size. The default page size is the - maximum value of 1000 results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListDataSourcesResponse(proto.Message): - r"""Returns list of supported data sources and their metadata. - Attributes: - data_sources (Sequence[google.cloud.bigquery_datatransfer_v1.types.DataSource]): - List of supported data sources and their - transfer settings. - next_page_token (str): - Output only. The next-pagination token. For multiple-page - list results, this token can be used as the - ``ListDataSourcesRequest.page_token`` to request the next - page of list results. - """ - - @property - def raw_page(self): - return self - - data_sources = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='DataSource', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateTransferConfigRequest(proto.Message): - r"""A request to create a data transfer configuration. If new - credentials are needed for this transfer configuration, an - authorization code must be provided. If an authorization code is - provided, the transfer configuration will be associated with the - user id corresponding to the authorization code. Otherwise, the - transfer configuration will be associated with the calling user. - - Attributes: - parent (str): - Required. The BigQuery project id where the transfer - configuration should be created. Must be in the format - projects/{project_id}/locations/{location_id} or - projects/{project_id}. If specified location and location of - the destination bigquery dataset do not match - the request - will fail. - transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): - Required. Data transfer configuration to - create. - authorization_code (str): - Optional OAuth2 authorization code to use with this transfer - configuration. This is required if new credentials are - needed, as indicated by ``CheckValidCreds``. In order to - obtain authorization_code, please make a request to - https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=&scope=&redirect_uri= - - - client_id should be OAuth client_id of BigQuery DTS API - for the given data source returned by ListDataSources - method. - - data_source_scopes are the scopes returned by - ListDataSources method. - - redirect_uri is an optional parameter. If not specified, - then authorization code is posted to the opener of - authorization flow window. Otherwise it will be sent to - the redirect uri. A special value of - urn:ietf:wg:oauth:2.0:oob means that authorization code - should be returned in the title bar of the browser, with - the page text prompting the user to copy the code and - paste it in the application. - version_info (str): - Optional version info. If users want to find a very recent - access token, that is, immediately after approving access, - users have to set the version_info claim in the token - request. To obtain the version_info, users must use the - "none+gsession" response type. which be return a - version_info back in the authorization response which be be - put in a JWT claim in the token request. - service_account_name (str): - Optional service account name. If this field - is set, transfer config will be created with - this service account credentials. It requires - that requesting user calling this API has - permissions to act as this service account. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - transfer_config = proto.Field( - proto.MESSAGE, - number=2, - message=transfer.TransferConfig, - ) - authorization_code = proto.Field( - proto.STRING, - number=3, - ) - version_info = proto.Field( - proto.STRING, - number=5, - ) - service_account_name = proto.Field( - proto.STRING, - number=6, - ) - - -class UpdateTransferConfigRequest(proto.Message): - r"""A request to update a transfer configuration. To update the - user id of the transfer configuration, an authorization code - needs to be provided. - - Attributes: - transfer_config (google.cloud.bigquery_datatransfer_v1.types.TransferConfig): - Required. Data transfer configuration to - create. - authorization_code (str): - Optional OAuth2 authorization code to use with this transfer - configuration. If it is provided, the transfer configuration - will be associated with the authorizing user. In order to - obtain authorization_code, please make a request to - https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=&scope=&redirect_uri= - - - client_id should be OAuth client_id of BigQuery DTS API - for the given data source returned by ListDataSources - method. - - data_source_scopes are the scopes returned by - ListDataSources method. - - redirect_uri is an optional parameter. If not specified, - then authorization code is posted to the opener of - authorization flow window. Otherwise it will be sent to - the redirect uri. A special value of - urn:ietf:wg:oauth:2.0:oob means that authorization code - should be returned in the title bar of the browser, with - the page text prompting the user to copy the code and - paste it in the application. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Required list of fields to be - updated in this request. - version_info (str): - Optional version info. If users want to find a very recent - access token, that is, immediately after approving access, - users have to set the version_info claim in the token - request. To obtain the version_info, users must use the - "none+gsession" response type. which be return a - version_info back in the authorization response which be be - put in a JWT claim in the token request. - service_account_name (str): - Optional service account name. If this field is set and - "service_account_name" is set in update_mask, transfer - config will be updated to use this service account - credentials. It requires that requesting user calling this - API has permissions to act as this service account. - """ - - transfer_config = proto.Field( - proto.MESSAGE, - number=1, - message=transfer.TransferConfig, - ) - authorization_code = proto.Field( - proto.STRING, - number=3, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - version_info = proto.Field( - proto.STRING, - number=5, - ) - service_account_name = proto.Field( - proto.STRING, - number=6, - ) - - -class GetTransferConfigRequest(proto.Message): - r"""A request to get data transfer information. - Attributes: - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteTransferConfigRequest(proto.Message): - r"""A request to delete data transfer information. All associated - transfer runs and log messages will be deleted as well. - - Attributes: - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetTransferRunRequest(proto.Message): - r"""A request to get data transfer run information. - Attributes: - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteTransferRunRequest(proto.Message): - r"""A request to delete data transfer run information. - Attributes: - name (str): - Required. The field will contain name of the resource - requested, for example: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListTransferConfigsRequest(proto.Message): - r"""A request to list data transfers configured for a BigQuery - project. - - Attributes: - parent (str): - Required. The BigQuery project id for which data sources - should be returned: ``projects/{project_id}`` or - ``projects/{project_id}/locations/{location_id}`` - data_source_ids (Sequence[str]): - When specified, only configurations of - requested data sources are returned. - page_token (str): - Pagination token, which can be used to request a specific - page of ``ListTransfersRequest`` list results. For - multiple-page results, ``ListTransfersResponse`` outputs a - ``next_page`` token, which can be used as the ``page_token`` - value to request the next page of list results. - page_size (int): - Page size. The default page size is the - maximum value of 1000 results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - data_source_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListTransferConfigsResponse(proto.Message): - r"""The returned list of pipelines in the project. - Attributes: - transfer_configs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): - Output only. The stored pipeline transfer - configurations. - next_page_token (str): - Output only. The next-pagination token. For multiple-page - list results, this token can be used as the - ``ListTransferConfigsRequest.page_token`` to request the - next page of list results. - """ - - @property - def raw_page(self): - return self - - transfer_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=transfer.TransferConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListTransferRunsRequest(proto.Message): - r"""A request to list data transfer runs. UI can use this method - to show/filter specific data transfer runs. The data source can - use this method to request all scheduled transfer runs. - - Attributes: - parent (str): - Required. Name of transfer configuration for which transfer - runs should be retrieved. Format of transfer configuration - resource name is: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - states (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferState]): - When specified, only transfer runs with - requested states are returned. - page_token (str): - Pagination token, which can be used to request a specific - page of ``ListTransferRunsRequest`` list results. For - multiple-page results, ``ListTransferRunsResponse`` outputs - a ``next_page`` token, which can be used as the - ``page_token`` value to request the next page of list - results. - page_size (int): - Page size. The default page size is the - maximum value of 1000 results. - run_attempt (google.cloud.bigquery_datatransfer_v1.types.ListTransferRunsRequest.RunAttempt): - Indicates how run attempts are to be pulled. - """ - class RunAttempt(proto.Enum): - r"""Represents which runs should be pulled.""" - RUN_ATTEMPT_UNSPECIFIED = 0 - LATEST = 1 - - parent = proto.Field( - proto.STRING, - number=1, - ) - states = proto.RepeatedField( - proto.ENUM, - number=2, - enum=transfer.TransferState, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - run_attempt = proto.Field( - proto.ENUM, - number=5, - enum=RunAttempt, - ) - - -class ListTransferRunsResponse(proto.Message): - r"""The returned list of pipelines in the project. - Attributes: - transfer_runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): - Output only. The stored pipeline transfer - runs. - next_page_token (str): - Output only. The next-pagination token. For multiple-page - list results, this token can be used as the - ``ListTransferRunsRequest.page_token`` to request the next - page of list results. - """ - - @property - def raw_page(self): - return self - - transfer_runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=transfer.TransferRun, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListTransferLogsRequest(proto.Message): - r"""A request to get user facing log messages associated with - data transfer run. - - Attributes: - parent (str): - Required. Transfer run name in the form: - ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`` - or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}/runs/{run_id}`` - page_token (str): - Pagination token, which can be used to request a specific - page of ``ListTransferLogsRequest`` list results. For - multiple-page results, ``ListTransferLogsResponse`` outputs - a ``next_page`` token, which can be used as the - ``page_token`` value to request the next page of list - results. - page_size (int): - Page size. The default page size is the - maximum value of 1000 results. - message_types (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferMessage.MessageSeverity]): - Message types to return. If not populated - - INFO, WARNING and ERROR messages are returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - page_size = proto.Field( - proto.INT32, - number=5, - ) - message_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=transfer.TransferMessage.MessageSeverity, - ) - - -class ListTransferLogsResponse(proto.Message): - r"""The returned list transfer run messages. - Attributes: - transfer_messages (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferMessage]): - Output only. The stored pipeline transfer - messages. - next_page_token (str): - Output only. The next-pagination token. For multiple-page - list results, this token can be used as the - ``GetTransferRunLogRequest.page_token`` to request the next - page of list results. - """ - - @property - def raw_page(self): - return self - - transfer_messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=transfer.TransferMessage, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CheckValidCredsRequest(proto.Message): - r"""A request to determine whether the user has valid - credentials. This method is used to limit the number of OAuth - popups in the user interface. The user id is inferred from the - API call context. - If the data source has the Google+ authorization type, this - method returns false, as it cannot be determined whether the - credentials are already valid merely based on the user id. - - Attributes: - name (str): - Required. The data source in the form: - ``projects/{project_id}/dataSources/{data_source_id}`` or - ``projects/{project_id}/locations/{location_id}/dataSources/{data_source_id}``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CheckValidCredsResponse(proto.Message): - r"""A response indicating whether the credentials exist and are - valid. - - Attributes: - has_valid_creds (bool): - If set to ``true``, the credentials exist and are valid. - """ - - has_valid_creds = proto.Field( - proto.BOOL, - number=1, - ) - - -class ScheduleTransferRunsRequest(proto.Message): - r"""A request to schedule transfer runs for a time range. - Attributes: - parent (str): - Required. Transfer configuration name in the form: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Start time of the range of transfer runs. For - example, ``"2017-05-25T00:00:00+00:00"``. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. End time of the range of transfer runs. For - example, ``"2017-05-30T00:00:00+00:00"``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - start_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ScheduleTransferRunsResponse(proto.Message): - r"""A response to schedule transfer runs for a time range. - Attributes: - runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): - The transfer runs that were scheduled. - """ - - runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=transfer.TransferRun, - ) - - -class StartManualTransferRunsRequest(proto.Message): - r"""A request to start manual transfer runs. - Attributes: - parent (str): - Transfer configuration name in the form: - ``projects/{project_id}/transferConfigs/{config_id}`` or - ``projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}``. - requested_time_range (google.cloud.bigquery_datatransfer_v1.types.StartManualTransferRunsRequest.TimeRange): - Time range for the transfer runs that should - be started. - requested_run_time (google.protobuf.timestamp_pb2.Timestamp): - Specific run_time for a transfer run to be started. The - requested_run_time must not be in the future. - """ - - class TimeRange(proto.Message): - r"""A specification for a time range, this will request transfer runs - with run_time between start_time (inclusive) and end_time - (exclusive). - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of the range of transfer runs. For example, - ``"2017-05-25T00:00:00+00:00"``. The start_time must be - strictly less than the end_time. Creates transfer runs where - run_time is in the range between start_time (inclusive) and - end_time (exclusive). - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of the range of transfer runs. For example, - ``"2017-05-30T00:00:00+00:00"``. The end_time must not be in - the future. Creates transfer runs where run_time is in the - range between start_time (inclusive) and end_time - (exclusive). - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - parent = proto.Field( - proto.STRING, - number=1, - ) - requested_time_range = proto.Field( - proto.MESSAGE, - number=3, - oneof='time', - message=TimeRange, - ) - requested_run_time = proto.Field( - proto.MESSAGE, - number=4, - oneof='time', - message=timestamp_pb2.Timestamp, - ) - - -class StartManualTransferRunsResponse(proto.Message): - r"""A response to start manual transfer runs. - Attributes: - runs (Sequence[google.cloud.bigquery_datatransfer_v1.types.TransferRun]): - The transfer runs that were created. - """ - - runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=transfer.TransferRun, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py b/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py deleted file mode 100644 index 1b04cb11..00000000 --- a/owl-bot-staging/v1/google/cloud/bigquery_datatransfer_v1/types/transfer.py +++ /dev/null @@ -1,442 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.bigquery.datatransfer.v1', - manifest={ - 'TransferType', - 'TransferState', - 'EmailPreferences', - 'ScheduleOptions', - 'TransferConfig', - 'TransferRun', - 'TransferMessage', - }, -) - - -class TransferType(proto.Enum): - r"""DEPRECATED. Represents data transfer type.""" - _pb_options = {'deprecated': True} - TRANSFER_TYPE_UNSPECIFIED = 0 - BATCH = 1 - STREAMING = 2 - - -class TransferState(proto.Enum): - r"""Represents data transfer run state.""" - TRANSFER_STATE_UNSPECIFIED = 0 - PENDING = 2 - RUNNING = 3 - SUCCEEDED = 4 - FAILED = 5 - CANCELLED = 6 - - -class EmailPreferences(proto.Message): - r"""Represents preferences for sending email notifications for - transfer run events. - - Attributes: - enable_failure_email (bool): - If true, email notifications will be sent on - transfer run failures. - """ - - enable_failure_email = proto.Field( - proto.BOOL, - number=1, - ) - - -class ScheduleOptions(proto.Message): - r"""Options customizing the data transfer schedule. - Attributes: - disable_auto_scheduling (bool): - If true, automatic scheduling of data - transfer runs for this configuration will be - disabled. The runs can be started on ad-hoc - basis using StartManualTransferRuns API. When - automatic scheduling is disabled, the - TransferConfig.schedule field will be ignored. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Specifies time to start scheduling transfer - runs. The first run will be scheduled at or - after the start time according to a recurrence - pattern defined in the schedule string. The - start time can be changed at any moment. The - time when a data transfer can be trigerred - manually is not limited by this option. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Defines time to stop scheduling transfer - runs. A transfer run cannot be scheduled at or - after the end time. The end time can be changed - at any moment. The time when a data transfer can - be trigerred manually is not limited by this - option. - """ - - disable_auto_scheduling = proto.Field( - proto.BOOL, - number=3, - ) - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class TransferConfig(proto.Message): - r"""Represents a data transfer configuration. A transfer configuration - contains all metadata needed to perform a data transfer. For - example, ``destination_dataset_id`` specifies where data should be - stored. When a new transfer configuration is created, the specified - ``destination_dataset_id`` is created when needed and shared with - the appropriate data source service account. - - Attributes: - name (str): - The resource name of the transfer config. Transfer config - names have the form - ``projects/{project_id}/locations/{region}/transferConfigs/{config_id}``. - Where ``config_id`` is usually a uuid, even though it is not - guaranteed or required. The name is ignored when creating a - transfer config. - destination_dataset_id (str): - The BigQuery target dataset id. - display_name (str): - User specified display name for the data - transfer. - data_source_id (str): - Data source id. Cannot be changed once data - transfer is created. - params (google.protobuf.struct_pb2.Struct): - Parameters specific to each data source. For - more information see the bq tab in the 'Setting - up a data transfer' section for each data - source. For example the parameters for Cloud - Storage transfers are listed here: - https://cloud.google.com/bigquery- - transfer/docs/cloud-storage-transfer#bq - schedule (str): - Data transfer schedule. If the data source does not support - a custom schedule, this should be empty. If it is empty, the - default value for the data source will be used. The - specified times are in UTC. Examples of valid format: - ``1st,3rd monday of month 15:30``, - ``every wed,fri of jan,jun 13:15``, and - ``first sunday of quarter 00:00``. See more explanation - about the format here: - https://cloud.google.com/appengine/docs/flexible/python/scheduling-jobs-with-cron-yaml#the_schedule_format - NOTE: the granularity should be at least 8 hours, or less - frequent. - schedule_options (google.cloud.bigquery_datatransfer_v1.types.ScheduleOptions): - Options customizing the data transfer - schedule. - data_refresh_window_days (int): - The number of days to look back to automatically refresh the - data. For example, if ``data_refresh_window_days = 10``, - then every day BigQuery reingests data for [today-10, - today-1], rather than ingesting data for just [today-1]. - Only valid if the data source supports the feature. Set the - value to 0 to use the default value. - disabled (bool): - Is this config disabled. When set to true, no - runs are scheduled for a given transfer. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Data transfer modification time. - Ignored by server on input. - next_run_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Next time when data transfer - will run. - state (google.cloud.bigquery_datatransfer_v1.types.TransferState): - Output only. State of the most recently - updated transfer run. - user_id (int): - Deprecated. Unique ID of the user on whose - behalf transfer is done. - dataset_region (str): - Output only. Region in which BigQuery dataset - is located. - notification_pubsub_topic (str): - Pub/Sub topic where notifications will be sent after - transfer runs associated with this transfer config finish. - - The format for specifying a pubsub topic is: - ``projects/{project}/topics/{topic}`` - email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): - Email notifications will be sent according to - these preferences to the email address of the - user who owns this transfer config. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - destination_dataset_id = proto.Field( - proto.STRING, - number=2, - oneof='destination', - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - data_source_id = proto.Field( - proto.STRING, - number=5, - ) - params = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - schedule = proto.Field( - proto.STRING, - number=7, - ) - schedule_options = proto.Field( - proto.MESSAGE, - number=24, - message='ScheduleOptions', - ) - data_refresh_window_days = proto.Field( - proto.INT32, - number=12, - ) - disabled = proto.Field( - proto.BOOL, - number=13, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - next_run_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=10, - enum='TransferState', - ) - user_id = proto.Field( - proto.INT64, - number=11, - ) - dataset_region = proto.Field( - proto.STRING, - number=14, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=15, - ) - email_preferences = proto.Field( - proto.MESSAGE, - number=18, - message='EmailPreferences', - ) - - -class TransferRun(proto.Message): - r"""Represents a data transfer run. - Attributes: - name (str): - The resource name of the transfer run. Transfer run names - have the form - ``projects/{project_id}/locations/{location}/transferConfigs/{config_id}/runs/{run_id}``. - The name is ignored when creating a transfer run. - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - Minimum time after which a transfer run can - be started. - run_time (google.protobuf.timestamp_pb2.Timestamp): - For batch transfer runs, specifies the date - and time of the data should be ingested. - error_status (google.rpc.status_pb2.Status): - Status of the transfer run. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when transfer run was - started. Parameter ignored by server for input - requests. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when transfer run ended. - Parameter ignored by server for input requests. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last time the data transfer run - state was updated. - params (google.protobuf.struct_pb2.Struct): - Output only. Parameters specific to each data - source. For more information see the bq tab in - the 'Setting up a data transfer' section for - each data source. For example the parameters for - Cloud Storage transfers are listed here: - https://cloud.google.com/bigquery- - transfer/docs/cloud-storage-transfer#bq - destination_dataset_id (str): - Output only. The BigQuery target dataset id. - data_source_id (str): - Output only. Data source id. - state (google.cloud.bigquery_datatransfer_v1.types.TransferState): - Data transfer run state. Ignored for input - requests. - user_id (int): - Deprecated. Unique ID of the user on whose - behalf transfer is done. - schedule (str): - Output only. Describes the schedule of this transfer run if - it was created as part of a regular schedule. For batch - transfer runs that are scheduled manually, this is empty. - NOTE: the system might choose to delay the schedule - depending on the current load, so ``schedule_time`` doesn't - always match this. - notification_pubsub_topic (str): - Output only. Pub/Sub topic where a notification will be sent - after this transfer run finishes. - - The format for specifying a pubsub topic is: - ``projects/{project}/topics/{topic}`` - email_preferences (google.cloud.bigquery_datatransfer_v1.types.EmailPreferences): - Output only. Email notifications will be sent - according to these preferences to the email - address of the user who owns the transfer config - this run was derived from. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - schedule_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - run_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - error_status = proto.Field( - proto.MESSAGE, - number=21, - message=status_pb2.Status, - ) - start_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - params = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - destination_dataset_id = proto.Field( - proto.STRING, - number=2, - oneof='destination', - ) - data_source_id = proto.Field( - proto.STRING, - number=7, - ) - state = proto.Field( - proto.ENUM, - number=8, - enum='TransferState', - ) - user_id = proto.Field( - proto.INT64, - number=11, - ) - schedule = proto.Field( - proto.STRING, - number=12, - ) - notification_pubsub_topic = proto.Field( - proto.STRING, - number=23, - ) - email_preferences = proto.Field( - proto.MESSAGE, - number=25, - message='EmailPreferences', - ) - - -class TransferMessage(proto.Message): - r"""Represents a user facing message for a particular data - transfer run. - - Attributes: - message_time (google.protobuf.timestamp_pb2.Timestamp): - Time when message was logged. - severity (google.cloud.bigquery_datatransfer_v1.types.TransferMessage.MessageSeverity): - Message severity. - message_text (str): - Message text. - """ - class MessageSeverity(proto.Enum): - r"""Represents data transfer user facing message severity.""" - MESSAGE_SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - - message_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - severity = proto.Field( - proto.ENUM, - number=2, - enum=MessageSeverity, - ) - message_text = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index ca28a557..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/bigquery_datatransfer_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py deleted file mode 100644 index f7746ab5..00000000 --- a/owl-bot-staging/v1/scripts/fixup_bigquery_datatransfer_v1_keywords.py +++ /dev/null @@ -1,189 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 bigquery_datatransferCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'check_valid_creds': ('name', ), - 'create_transfer_config': ('parent', 'transfer_config', 'authorization_code', 'version_info', 'service_account_name', ), - 'delete_transfer_config': ('name', ), - 'delete_transfer_run': ('name', ), - 'get_data_source': ('name', ), - 'get_transfer_config': ('name', ), - 'get_transfer_run': ('name', ), - 'list_data_sources': ('parent', 'page_token', 'page_size', ), - 'list_transfer_configs': ('parent', 'data_source_ids', 'page_token', 'page_size', ), - 'list_transfer_logs': ('parent', 'page_token', 'page_size', 'message_types', ), - 'list_transfer_runs': ('parent', 'states', 'page_token', 'page_size', 'run_attempt', ), - 'schedule_transfer_runs': ('parent', 'start_time', 'end_time', ), - 'start_manual_transfer_runs': ('parent', 'requested_time_range', 'requested_run_time', ), - 'update_transfer_config': ('transfer_config', 'update_mask', 'authorization_code', 'version_info', 'service_account_name', ), - } - - 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: not a.keyword.value 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=bigquery_datatransferCallTransformer(), -): - """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 bigquery_datatransfer client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 4c0a253d..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-bigquery-datatransfer', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py b/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py deleted file mode 100644 index 5d484a61..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py +++ /dev/null @@ -1,5087 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import DataTransferServiceAsyncClient -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import DataTransferServiceClient -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import pagers -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service import transports -from google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.bigquery_datatransfer_v1.types import datatransfer -from google.cloud.bigquery_datatransfer_v1.types import transfer -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DataTransferServiceClient._get_default_mtls_endpoint(None) is None - assert DataTransferServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataTransferServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataTransferServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataTransferServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataTransferServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DataTransferServiceClient, - DataTransferServiceAsyncClient, -]) -def test_data_transfer_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DataTransferServiceGrpcTransport, "grpc"), - (transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_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", [ - DataTransferServiceClient, - DataTransferServiceAsyncClient, -]) -def test_data_transfer_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' - - -def test_data_transfer_service_client_get_transport_class(): - transport = DataTransferServiceClient.get_transport_class() - available_transports = [ - transports.DataTransferServiceGrpcTransport, - ] - assert transport in available_transports - - transport = DataTransferServiceClient.get_transport_class("grpc") - assert transport == transports.DataTransferServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), - (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DataTransferServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceClient)) -@mock.patch.object(DataTransferServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceAsyncClient)) -def test_data_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(DataTransferServiceClient, '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(DataTransferServiceClient, '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(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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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() - 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, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc", "true"), - (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc", "false"), - (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DataTransferServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceClient)) -@mock.patch.object(DataTransferServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataTransferServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - 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, - ) - - # 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() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), - (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataTransferServiceClient, transports.DataTransferServiceGrpcTransport, "grpc"), - (DataTransferServiceAsyncClient, transports.DataTransferServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_transfer_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_data_transfer_service_client_client_options_from_dict(): - with mock.patch('google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DataTransferServiceClient( - 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, - ) - - -def test_get_data_source(transport: str = 'grpc', request_type=datatransfer.GetDataSourceRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.DataSource( - name='name_value', - data_source_id='data_source_id_value', - display_name='display_name_value', - description='description_value', - client_id='client_id_value', - scopes=['scopes_value'], - transfer_type=transfer.TransferType.BATCH, - supports_multiple_transfers=True, - update_deadline_seconds=2406, - default_schedule='default_schedule_value', - supports_custom_schedule=True, - help_url='help_url_value', - authorization_type=datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE, - data_refresh_type=datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW, - default_data_refresh_window_days=3379, - manual_runs_disabled=True, - ) - response = client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetDataSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.client_id == 'client_id_value' - assert response.scopes == ['scopes_value'] - assert response.transfer_type == transfer.TransferType.BATCH - assert response.supports_multiple_transfers is True - assert response.update_deadline_seconds == 2406 - assert response.default_schedule == 'default_schedule_value' - assert response.supports_custom_schedule is True - assert response.help_url == 'help_url_value' - assert response.authorization_type == datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE - assert response.data_refresh_type == datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW - assert response.default_data_refresh_window_days == 3379 - assert response.manual_runs_disabled is True - - -def test_get_data_source_from_dict(): - test_get_data_source(request_type=dict) - - -def test_get_data_source_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 = DataTransferServiceClient( - 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_data_source), - '__call__') as call: - client.get_data_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetDataSourceRequest() - - -@pytest.mark.asyncio -async def test_get_data_source_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetDataSourceRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource( - name='name_value', - data_source_id='data_source_id_value', - display_name='display_name_value', - description='description_value', - client_id='client_id_value', - scopes=['scopes_value'], - transfer_type=transfer.TransferType.BATCH, - supports_multiple_transfers=True, - update_deadline_seconds=2406, - default_schedule='default_schedule_value', - supports_custom_schedule=True, - help_url='help_url_value', - authorization_type=datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE, - data_refresh_type=datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW, - default_data_refresh_window_days=3379, - manual_runs_disabled=True, - )) - response = await client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetDataSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.DataSource) - assert response.name == 'name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.client_id == 'client_id_value' - assert response.scopes == ['scopes_value'] - assert response.transfer_type == transfer.TransferType.BATCH - assert response.supports_multiple_transfers is True - assert response.update_deadline_seconds == 2406 - assert response.default_schedule == 'default_schedule_value' - assert response.supports_custom_schedule is True - assert response.help_url == 'help_url_value' - assert response.authorization_type == datatransfer.DataSource.AuthorizationType.AUTHORIZATION_CODE - assert response.data_refresh_type == datatransfer.DataSource.DataRefreshType.SLIDING_WINDOW - assert response.default_data_refresh_window_days == 3379 - assert response.manual_runs_disabled is True - - -@pytest.mark.asyncio -async def test_get_data_source_async_from_dict(): - await test_get_data_source_async(request_type=dict) - - -def test_get_data_source_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetDataSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value = datatransfer.DataSource() - client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_data_source_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetDataSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource()) - await client.get_data_source(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_data_source_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.DataSource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_data_source( - 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] - assert args[0].name == 'name_value' - - -def test_get_data_source_flattened_error(): - client = DataTransferServiceClient( - 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_data_source( - datatransfer.GetDataSourceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_data_source_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.DataSource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.DataSource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_data_source( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_data_source_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_data_source( - datatransfer.GetDataSourceRequest(), - name='name_value', - ) - - -def test_list_data_sources(transport: str = 'grpc', request_type=datatransfer.ListDataSourcesRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListDataSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListDataSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_data_sources_from_dict(): - test_list_data_sources(request_type=dict) - - -def test_list_data_sources_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 = DataTransferServiceClient( - 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_data_sources), - '__call__') as call: - client.list_data_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListDataSourcesRequest() - - -@pytest.mark.asyncio -async def test_list_data_sources_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListDataSourcesRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListDataSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_data_sources_async_from_dict(): - await test_list_data_sources_async(request_type=dict) - - -def test_list_data_sources_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListDataSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - call.return_value = datatransfer.ListDataSourcesResponse() - client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_data_sources_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListDataSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse()) - await client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_data_sources_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListDataSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_data_sources( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_data_sources_flattened_error(): - client = DataTransferServiceClient( - 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_data_sources( - datatransfer.ListDataSourcesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_data_sources_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListDataSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListDataSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_data_sources( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_data_sources_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_data_sources( - datatransfer.ListDataSourcesRequest(), - parent='parent_value', - ) - - -def test_list_data_sources_pager(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - next_page_token='abc', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - ], - next_page_token='ghi', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_data_sources(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, datatransfer.DataSource) - for i in results) - -def test_list_data_sources_pages(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - next_page_token='abc', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - ], - next_page_token='ghi', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_data_sources(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_data_sources_async_pager(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - next_page_token='abc', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - ], - next_page_token='ghi', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_data_sources(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, datatransfer.DataSource) - for i in responses) - -@pytest.mark.asyncio -async def test_list_data_sources_async_pages(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - next_page_token='abc', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[], - next_page_token='def', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - ], - next_page_token='ghi', - ), - datatransfer.ListDataSourcesResponse( - data_sources=[ - datatransfer.DataSource(), - datatransfer.DataSource(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_data_sources(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_create_transfer_config(transport: str = 'grpc', request_type=datatransfer.CreateTransferConfigRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - destination_dataset_id='destination_dataset_id_value', - ) - response = client.create_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CreateTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -def test_create_transfer_config_from_dict(): - test_create_transfer_config(request_type=dict) - - -def test_create_transfer_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataTransferServiceClient( - 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_config), - '__call__') as call: - client.create_transfer_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CreateTransferConfigRequest() - - -@pytest.mark.asyncio -async def test_create_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.CreateTransferConfigRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - )) - response = await client.create_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CreateTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -@pytest.mark.asyncio -async def test_create_transfer_config_async_from_dict(): - await test_create_transfer_config_async(request_type=dict) - - -def test_create_transfer_config_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.CreateTransferConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transfer_config), - '__call__') as call: - call.return_value = transfer.TransferConfig() - client.create_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_transfer_config_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.CreateTransferConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transfer_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - await client.create_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_transfer_config_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_transfer_config( - parent='parent_value', - transfer_config=transfer.TransferConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].transfer_config == transfer.TransferConfig(name='name_value') - - -def test_create_transfer_config_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_config( - datatransfer.CreateTransferConfigRequest(), - parent='parent_value', - transfer_config=transfer.TransferConfig(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_transfer_config_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_transfer_config( - parent='parent_value', - transfer_config=transfer.TransferConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].transfer_config == transfer.TransferConfig(name='name_value') - - -@pytest.mark.asyncio -async def test_create_transfer_config_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_config( - datatransfer.CreateTransferConfigRequest(), - parent='parent_value', - transfer_config=transfer.TransferConfig(name='name_value'), - ) - - -def test_update_transfer_config(transport: str = 'grpc', request_type=datatransfer.UpdateTransferConfigRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - destination_dataset_id='destination_dataset_id_value', - ) - response = client.update_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.UpdateTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -def test_update_transfer_config_from_dict(): - test_update_transfer_config(request_type=dict) - - -def test_update_transfer_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataTransferServiceClient( - 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_config), - '__call__') as call: - client.update_transfer_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.UpdateTransferConfigRequest() - - -@pytest.mark.asyncio -async def test_update_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.UpdateTransferConfigRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - )) - response = await client.update_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.UpdateTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -@pytest.mark.asyncio -async def test_update_transfer_config_async_from_dict(): - await test_update_transfer_config_async(request_type=dict) - - -def test_update_transfer_config_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.UpdateTransferConfigRequest() - - request.transfer_config.name = 'transfer_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transfer_config), - '__call__') as call: - call.return_value = transfer.TransferConfig() - client.update_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transfer_config.name=transfer_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_transfer_config_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.UpdateTransferConfigRequest() - - request.transfer_config.name = 'transfer_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transfer_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - await client.update_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transfer_config.name=transfer_config.name/value', - ) in kw['metadata'] - - -def test_update_transfer_config_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_transfer_config( - transfer_config=transfer.TransferConfig(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] - assert args[0].transfer_config == transfer.TransferConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_transfer_config_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_config( - datatransfer.UpdateTransferConfigRequest(), - transfer_config=transfer.TransferConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_transfer_config_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_transfer_config( - transfer_config=transfer.TransferConfig(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] - assert args[0].transfer_config == transfer.TransferConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_transfer_config_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_config( - datatransfer.UpdateTransferConfigRequest(), - transfer_config=transfer.TransferConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_transfer_config(transport: str = 'grpc', request_type=datatransfer.DeleteTransferConfigRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_transfer_config_from_dict(): - test_delete_transfer_config(request_type=dict) - - -def test_delete_transfer_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataTransferServiceClient( - 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_config), - '__call__') as call: - client.delete_transfer_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.DeleteTransferConfigRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_transfer_config_async_from_dict(): - await test_delete_transfer_config_async(request_type=dict) - - -def test_delete_transfer_config_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.DeleteTransferConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_config), - '__call__') as call: - call.return_value = None - client.delete_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_transfer_config_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.DeleteTransferConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_transfer_config_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_transfer_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_transfer_config_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_config( - datatransfer.DeleteTransferConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_transfer_config_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_transfer_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_transfer_config_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_config( - datatransfer.DeleteTransferConfigRequest(), - name='name_value', - ) - - -def test_get_transfer_config(transport: str = 'grpc', request_type=datatransfer.GetTransferConfigRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - destination_dataset_id='destination_dataset_id_value', - ) - response = client.get_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -def test_get_transfer_config_from_dict(): - test_get_transfer_config(request_type=dict) - - -def test_get_transfer_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataTransferServiceClient( - 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_config), - '__call__') as call: - client.get_transfer_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferConfigRequest() - - -@pytest.mark.asyncio -async def test_get_transfer_config_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetTransferConfigRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig( - name='name_value', - display_name='display_name_value', - data_source_id='data_source_id_value', - schedule='schedule_value', - data_refresh_window_days=2543, - disabled=True, - state=transfer.TransferState.PENDING, - user_id=747, - dataset_region='dataset_region_value', - notification_pubsub_topic='notification_pubsub_topic_value', - )) - response = await client.get_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.schedule == 'schedule_value' - assert response.data_refresh_window_days == 2543 - assert response.disabled is True - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.dataset_region == 'dataset_region_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -@pytest.mark.asyncio -async def test_get_transfer_config_async_from_dict(): - await test_get_transfer_config_async(request_type=dict) - - -def test_get_transfer_config_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetTransferConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_config), - '__call__') as call: - call.return_value = transfer.TransferConfig() - client.get_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_transfer_config_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetTransferConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - await client.get_transfer_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_transfer_config_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_transfer_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_transfer_config_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_config( - datatransfer.GetTransferConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_transfer_config_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_transfer_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_transfer_config_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_config( - datatransfer.GetTransferConfigRequest(), - name='name_value', - ) - - -def test_list_transfer_configs(transport: str = 'grpc', request_type=datatransfer.ListTransferConfigsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_transfer_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_transfer_configs_from_dict(): - test_list_transfer_configs(request_type=dict) - - -def test_list_transfer_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataTransferServiceClient( - 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_configs), - '__call__') as call: - client.list_transfer_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_transfer_configs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferConfigsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_transfer_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_transfer_configs_async_from_dict(): - await test_list_transfer_configs_async(request_type=dict) - - -def test_list_transfer_configs_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_configs), - '__call__') as call: - call.return_value = datatransfer.ListTransferConfigsResponse() - client.list_transfer_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_transfer_configs_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse()) - await client.list_transfer_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_transfer_configs_flattened(): - client = DataTransferServiceClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_transfer_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_transfer_configs_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_configs( - datatransfer.ListTransferConfigsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_transfer_configs_flattened_async(): - client = DataTransferServiceAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_transfer_configs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_transfer_configs_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_configs( - datatransfer.ListTransferConfigsRequest(), - parent='parent_value', - ) - - -def test_list_transfer_configs_pager(): - client = DataTransferServiceClient( - 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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[], - next_page_token='def', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_transfer_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, transfer.TransferConfig) - for i in results) - -def test_list_transfer_configs_pages(): - client = DataTransferServiceClient( - 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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[], - next_page_token='def', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_transfer_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_transfer_configs_async_pager(): - client = DataTransferServiceAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[], - next_page_token='def', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_transfer_configs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, transfer.TransferConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_transfer_configs_async_pages(): - client = DataTransferServiceAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[], - next_page_token='def', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferConfigsResponse( - transfer_configs=[ - transfer.TransferConfig(), - transfer.TransferConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_transfer_configs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_schedule_transfer_runs(transport: str = 'grpc', request_type=datatransfer.ScheduleTransferRunsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ScheduleTransferRunsResponse( - ) - response = client.schedule_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ScheduleTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.ScheduleTransferRunsResponse) - - -def test_schedule_transfer_runs_from_dict(): - test_schedule_transfer_runs(request_type=dict) - - -def test_schedule_transfer_runs_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 = DataTransferServiceClient( - 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.schedule_transfer_runs), - '__call__') as call: - client.schedule_transfer_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ScheduleTransferRunsRequest() - - -@pytest.mark.asyncio -async def test_schedule_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ScheduleTransferRunsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse( - )) - response = await client.schedule_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ScheduleTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.ScheduleTransferRunsResponse) - - -@pytest.mark.asyncio -async def test_schedule_transfer_runs_async_from_dict(): - await test_schedule_transfer_runs_async(request_type=dict) - - -def test_schedule_transfer_runs_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ScheduleTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - call.return_value = datatransfer.ScheduleTransferRunsResponse() - client.schedule_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_schedule_transfer_runs_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ScheduleTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse()) - await client.schedule_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_schedule_transfer_runs_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ScheduleTransferRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.schedule_transfer_runs( - parent='parent_value', - start_time=timestamp_pb2.Timestamp(seconds=751), - end_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - assert TimestampRule().to_proto(args[0].end_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_schedule_transfer_runs_flattened_error(): - client = DataTransferServiceClient( - 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.schedule_transfer_runs( - datatransfer.ScheduleTransferRunsRequest(), - parent='parent_value', - start_time=timestamp_pb2.Timestamp(seconds=751), - end_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.asyncio -async def test_schedule_transfer_runs_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ScheduleTransferRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ScheduleTransferRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.schedule_transfer_runs( - parent='parent_value', - start_time=timestamp_pb2.Timestamp(seconds=751), - end_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - assert TimestampRule().to_proto(args[0].end_time) == timestamp_pb2.Timestamp(seconds=751) - - -@pytest.mark.asyncio -async def test_schedule_transfer_runs_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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.schedule_transfer_runs( - datatransfer.ScheduleTransferRunsRequest(), - parent='parent_value', - start_time=timestamp_pb2.Timestamp(seconds=751), - end_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_start_manual_transfer_runs(transport: str = 'grpc', request_type=datatransfer.StartManualTransferRunsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_manual_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.StartManualTransferRunsResponse( - ) - response = client.start_manual_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.StartManualTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.StartManualTransferRunsResponse) - - -def test_start_manual_transfer_runs_from_dict(): - test_start_manual_transfer_runs(request_type=dict) - - -def test_start_manual_transfer_runs_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 = DataTransferServiceClient( - 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.start_manual_transfer_runs), - '__call__') as call: - client.start_manual_transfer_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.StartManualTransferRunsRequest() - - -@pytest.mark.asyncio -async def test_start_manual_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.StartManualTransferRunsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_manual_transfer_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.StartManualTransferRunsResponse( - )) - response = await client.start_manual_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.StartManualTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.StartManualTransferRunsResponse) - - -@pytest.mark.asyncio -async def test_start_manual_transfer_runs_async_from_dict(): - await test_start_manual_transfer_runs_async(request_type=dict) - - -def test_start_manual_transfer_runs_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.StartManualTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_manual_transfer_runs), - '__call__') as call: - call.return_value = datatransfer.StartManualTransferRunsResponse() - client.start_manual_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_start_manual_transfer_runs_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.StartManualTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_manual_transfer_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.StartManualTransferRunsResponse()) - await client.start_manual_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_get_transfer_run(transport: str = 'grpc', request_type=datatransfer.GetTransferRunRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferRun( - name='name_value', - data_source_id='data_source_id_value', - state=transfer.TransferState.PENDING, - user_id=747, - schedule='schedule_value', - notification_pubsub_topic='notification_pubsub_topic_value', - destination_dataset_id='destination_dataset_id_value', - ) - response = client.get_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferRun) - assert response.name == 'name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.schedule == 'schedule_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -def test_get_transfer_run_from_dict(): - test_get_transfer_run(request_type=dict) - - -def test_get_transfer_run_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 = DataTransferServiceClient( - 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_run), - '__call__') as call: - client.get_transfer_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferRunRequest() - - -@pytest.mark.asyncio -async def test_get_transfer_run_async(transport: str = 'grpc_asyncio', request_type=datatransfer.GetTransferRunRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun( - name='name_value', - data_source_id='data_source_id_value', - state=transfer.TransferState.PENDING, - user_id=747, - schedule='schedule_value', - notification_pubsub_topic='notification_pubsub_topic_value', - )) - response = await client.get_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.GetTransferRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transfer.TransferRun) - assert response.name == 'name_value' - assert response.data_source_id == 'data_source_id_value' - assert response.state == transfer.TransferState.PENDING - assert response.user_id == 747 - assert response.schedule == 'schedule_value' - assert response.notification_pubsub_topic == 'notification_pubsub_topic_value' - - -@pytest.mark.asyncio -async def test_get_transfer_run_async_from_dict(): - await test_get_transfer_run_async(request_type=dict) - - -def test_get_transfer_run_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetTransferRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_run), - '__call__') as call: - call.return_value = transfer.TransferRun() - client.get_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_transfer_run_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.GetTransferRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun()) - await client.get_transfer_run(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_transfer_run_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_transfer_run( - 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] - assert args[0].name == 'name_value' - - -def test_get_transfer_run_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_run( - datatransfer.GetTransferRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_transfer_run_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transfer_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transfer.TransferRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transfer.TransferRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_transfer_run( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_transfer_run_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_run( - datatransfer.GetTransferRunRequest(), - name='name_value', - ) - - -def test_delete_transfer_run(transport: str = 'grpc', request_type=datatransfer.DeleteTransferRunRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferRunRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_transfer_run_from_dict(): - test_delete_transfer_run(request_type=dict) - - -def test_delete_transfer_run_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 = DataTransferServiceClient( - 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_run), - '__call__') as call: - client.delete_transfer_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferRunRequest() - - -@pytest.mark.asyncio -async def test_delete_transfer_run_async(transport: str = 'grpc_asyncio', request_type=datatransfer.DeleteTransferRunRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.DeleteTransferRunRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_transfer_run_async_from_dict(): - await test_delete_transfer_run_async(request_type=dict) - - -def test_delete_transfer_run_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.DeleteTransferRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_run), - '__call__') as call: - call.return_value = None - client.delete_transfer_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_transfer_run_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.DeleteTransferRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transfer_run(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_transfer_run_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_run), - '__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_transfer_run( - 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] - assert args[0].name == 'name_value' - - -def test_delete_transfer_run_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_run( - datatransfer.DeleteTransferRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_transfer_run_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transfer_run), - '__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_transfer_run( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_transfer_run_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_run( - datatransfer.DeleteTransferRunRequest(), - name='name_value', - ) - - -def test_list_transfer_runs(transport: str = 'grpc', request_type=datatransfer.ListTransferRunsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_transfer_runs_from_dict(): - test_list_transfer_runs(request_type=dict) - - -def test_list_transfer_runs_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 = DataTransferServiceClient( - 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_runs), - '__call__') as call: - client.list_transfer_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferRunsRequest() - - -@pytest.mark.asyncio -async def test_list_transfer_runs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferRunsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_transfer_runs_async_from_dict(): - await test_list_transfer_runs_async(request_type=dict) - - -def test_list_transfer_runs_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_runs), - '__call__') as call: - call.return_value = datatransfer.ListTransferRunsResponse() - client.list_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_transfer_runs_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse()) - await client.list_transfer_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_transfer_runs_flattened(): - client = DataTransferServiceClient( - 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_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_transfer_runs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_transfer_runs_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_runs( - datatransfer.ListTransferRunsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_transfer_runs_flattened_async(): - client = DataTransferServiceAsyncClient( - 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_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_transfer_runs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_transfer_runs_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_runs( - datatransfer.ListTransferRunsRequest(), - parent='parent_value', - ) - - -def test_list_transfer_runs_pager(): - client = DataTransferServiceClient( - 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_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - transfer.TransferRun(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[], - next_page_token='def', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_transfer_runs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, transfer.TransferRun) - for i in results) - -def test_list_transfer_runs_pages(): - client = DataTransferServiceClient( - 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_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - transfer.TransferRun(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[], - next_page_token='def', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_transfer_runs(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_runs_async_pager(): - client = DataTransferServiceAsyncClient( - 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_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - transfer.TransferRun(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[], - next_page_token='def', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_transfer_runs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, transfer.TransferRun) - for i in responses) - -@pytest.mark.asyncio -async def test_list_transfer_runs_async_pages(): - client = DataTransferServiceAsyncClient( - 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_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - transfer.TransferRun(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[], - next_page_token='def', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferRunsResponse( - transfer_runs=[ - transfer.TransferRun(), - transfer.TransferRun(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_transfer_runs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_transfer_logs(transport: str = 'grpc', request_type=datatransfer.ListTransferLogsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferLogsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_transfer_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferLogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferLogsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_transfer_logs_from_dict(): - test_list_transfer_logs(request_type=dict) - - -def test_list_transfer_logs_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 = DataTransferServiceClient( - 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_logs), - '__call__') as call: - client.list_transfer_logs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferLogsRequest() - - -@pytest.mark.asyncio -async def test_list_transfer_logs_async(transport: str = 'grpc_asyncio', request_type=datatransfer.ListTransferLogsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_transfer_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.ListTransferLogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransferLogsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_transfer_logs_async_from_dict(): - await test_list_transfer_logs_async(request_type=dict) - - -def test_list_transfer_logs_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferLogsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_logs), - '__call__') as call: - call.return_value = datatransfer.ListTransferLogsResponse() - client.list_transfer_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_transfer_logs_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.ListTransferLogsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transfer_logs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse()) - await client.list_transfer_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_transfer_logs_flattened(): - client = DataTransferServiceClient( - 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferLogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_transfer_logs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_transfer_logs_flattened_error(): - client = DataTransferServiceClient( - 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_transfer_logs( - datatransfer.ListTransferLogsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_transfer_logs_flattened_async(): - client = DataTransferServiceAsyncClient( - 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.ListTransferLogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.ListTransferLogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_transfer_logs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_transfer_logs_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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_transfer_logs( - datatransfer.ListTransferLogsRequest(), - parent='parent_value', - ) - - -def test_list_transfer_logs_pager(): - client = DataTransferServiceClient( - 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_logs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[], - next_page_token='def', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_transfer_logs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, transfer.TransferMessage) - for i in results) - -def test_list_transfer_logs_pages(): - client = DataTransferServiceClient( - 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_logs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[], - next_page_token='def', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - ), - RuntimeError, - ) - pages = list(client.list_transfer_logs(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_logs_async_pager(): - client = DataTransferServiceAsyncClient( - 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_logs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[], - next_page_token='def', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_transfer_logs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, transfer.TransferMessage) - for i in responses) - -@pytest.mark.asyncio -async def test_list_transfer_logs_async_pages(): - client = DataTransferServiceAsyncClient( - 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_logs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - next_page_token='abc', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[], - next_page_token='def', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - ], - next_page_token='ghi', - ), - datatransfer.ListTransferLogsResponse( - transfer_messages=[ - transfer.TransferMessage(), - transfer.TransferMessage(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_transfer_logs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_check_valid_creds(transport: str = 'grpc', request_type=datatransfer.CheckValidCredsRequest): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.CheckValidCredsResponse( - has_valid_creds=True, - ) - response = client.check_valid_creds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CheckValidCredsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.CheckValidCredsResponse) - assert response.has_valid_creds is True - - -def test_check_valid_creds_from_dict(): - test_check_valid_creds(request_type=dict) - - -def test_check_valid_creds_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 = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - client.check_valid_creds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CheckValidCredsRequest() - - -@pytest.mark.asyncio -async def test_check_valid_creds_async(transport: str = 'grpc_asyncio', request_type=datatransfer.CheckValidCredsRequest): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse( - has_valid_creds=True, - )) - response = await client.check_valid_creds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datatransfer.CheckValidCredsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datatransfer.CheckValidCredsResponse) - assert response.has_valid_creds is True - - -@pytest.mark.asyncio -async def test_check_valid_creds_async_from_dict(): - await test_check_valid_creds_async(request_type=dict) - - -def test_check_valid_creds_field_headers(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.CheckValidCredsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - call.return_value = datatransfer.CheckValidCredsResponse() - client.check_valid_creds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_check_valid_creds_field_headers_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datatransfer.CheckValidCredsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse()) - await client.check_valid_creds(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_check_valid_creds_flattened(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.CheckValidCredsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.check_valid_creds( - 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] - assert args[0].name == 'name_value' - - -def test_check_valid_creds_flattened_error(): - client = DataTransferServiceClient( - 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.check_valid_creds( - datatransfer.CheckValidCredsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_check_valid_creds_flattened_async(): - client = DataTransferServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_valid_creds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datatransfer.CheckValidCredsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datatransfer.CheckValidCredsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.check_valid_creds( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_check_valid_creds_flattened_error_async(): - client = DataTransferServiceAsyncClient( - 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.check_valid_creds( - datatransfer.CheckValidCredsRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DataTransferServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DataTransferServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataTransferServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DataTransferServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataTransferServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataTransferServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DataTransferServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataTransferServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DataTransferServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DataTransferServiceGrpcTransport, - transports.DataTransferServiceGrpcAsyncIOTransport, -]) -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() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DataTransferServiceGrpcTransport, - ) - -def test_data_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.DataTransferServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_data_transfer_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DataTransferServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_data_source', - 'list_data_sources', - 'create_transfer_config', - 'update_transfer_config', - 'delete_transfer_config', - 'get_transfer_config', - 'list_transfer_configs', - 'schedule_transfer_runs', - 'start_manual_transfer_runs', - 'get_transfer_run', - 'delete_transfer_run', - 'list_transfer_runs', - 'list_transfer_logs', - 'check_valid_creds', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_data_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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataTransferServiceTransport( - 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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_data_transfer_service_base_transport_with_credentials_file_old_google_auth(): - # 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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataTransferServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_data_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.bigquery_datatransfer_v1.services.data_transfer_service.transports.DataTransferServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataTransferServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_data_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) - DataTransferServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_data_transfer_service_auth_adc_old_google_auth(): - # 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) - DataTransferServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DataTransferServiceGrpcTransport, - transports.DataTransferServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_data_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.DataTransferServiceGrpcTransport, - transports.DataTransferServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_data_transfer_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DataTransferServiceGrpcTransport, grpc_helpers), - (transports.DataTransferServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_data_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( - "bigquerydatatransfer.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="bigquerydatatransfer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) -def test_data_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_data_transfer_service_host_no_port(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='bigquerydatatransfer.googleapis.com'), - ) - assert client.transport._host == 'bigquerydatatransfer.googleapis.com:443' - - -def test_data_transfer_service_host_with_port(): - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='bigquerydatatransfer.googleapis.com:8000'), - ) - assert client.transport._host == 'bigquerydatatransfer.googleapis.com:8000' - -def test_data_transfer_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataTransferServiceGrpcTransport( - 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_data_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.DataTransferServiceGrpcAsyncIOTransport( - 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.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) -def test_data_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.DataTransferServiceGrpcTransport, transports.DataTransferServiceGrpcAsyncIOTransport]) -def test_data_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_data_source_path(): - project = "squid" - data_source = "clam" - expected = "projects/{project}/dataSources/{data_source}".format(project=project, data_source=data_source, ) - actual = DataTransferServiceClient.data_source_path(project, data_source) - assert expected == actual - - -def test_parse_data_source_path(): - expected = { - "project": "whelk", - "data_source": "octopus", - } - path = DataTransferServiceClient.data_source_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_data_source_path(path) - assert expected == actual - -def test_run_path(): - project = "oyster" - transfer_config = "nudibranch" - run = "cuttlefish" - expected = "projects/{project}/transferConfigs/{transfer_config}/runs/{run}".format(project=project, transfer_config=transfer_config, run=run, ) - actual = DataTransferServiceClient.run_path(project, transfer_config, run) - assert expected == actual - - -def test_parse_run_path(): - expected = { - "project": "mussel", - "transfer_config": "winkle", - "run": "nautilus", - } - path = DataTransferServiceClient.run_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_run_path(path) - assert expected == actual - -def test_transfer_config_path(): - project = "scallop" - transfer_config = "abalone" - expected = "projects/{project}/transferConfigs/{transfer_config}".format(project=project, transfer_config=transfer_config, ) - actual = DataTransferServiceClient.transfer_config_path(project, transfer_config) - assert expected == actual - - -def test_parse_transfer_config_path(): - expected = { - "project": "squid", - "transfer_config": "clam", - } - path = DataTransferServiceClient.transfer_config_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_transfer_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DataTransferServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = DataTransferServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = DataTransferServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = DataTransferServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DataTransferServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = DataTransferServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = DataTransferServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = DataTransferServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DataTransferServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = DataTransferServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DataTransferServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DataTransferServiceTransport, '_prep_wrapped_messages') as prep: - client = DataTransferServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DataTransferServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DataTransferServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info)