From 3b52c5b04b59d6d2834bbb8fd68d8f9ed8a5475b Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 8 Nov 2021 10:48:30 +0000 Subject: [PATCH 1/3] feat: Added BigQueryDateShardedSpec.latest_shard_resource field feat: Added SearchCatalogResult.display_name field feat: Added SearchCatalogResult.description field PiperOrigin-RevId: 408274419 Source-Link: https://github.com/googleapis/googleapis/commit/cbba92c063e7d9752bf6e5d8f5081a84a5e7f159 Source-Link: https://github.com/googleapis/googleapis-gen/commit/64b969f1299f572fbb269530cbc454966b14851d Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjRiOTY5ZjEyOTlmNTcyZmJiMjY5NTMwY2JjNDU0OTY2YjE0ODUxZCJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 + .../v1/docs/datacatalog_v1/data_catalog.rst | 10 + .../datacatalog_v1/policy_tag_manager.rst | 10 + .../policy_tag_manager_serialization.rst | 6 + .../v1/docs/datacatalog_v1/services.rst | 8 + .../v1/docs/datacatalog_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/datacatalog/__init__.py | 195 + .../v1/google/cloud/datacatalog/py.typed | 2 + .../google/cloud/datacatalog_v1/__init__.py | 196 + .../cloud/datacatalog_v1/gapic_metadata.json | 491 + .../v1/google/cloud/datacatalog_v1/py.typed | 2 + .../cloud/datacatalog_v1/services/__init__.py | 15 + .../services/data_catalog/__init__.py | 22 + .../services/data_catalog/async_client.py | 3009 ++++++ .../services/data_catalog/client.py | 3201 +++++++ .../services/data_catalog/pagers.py | 508 + .../data_catalog/transports/__init__.py | 33 + .../services/data_catalog/transports/base.py | 576 ++ .../services/data_catalog/transports/grpc.py | 1161 +++ .../data_catalog/transports/grpc_asyncio.py | 1165 +++ .../services/policy_tag_manager/__init__.py | 22 + .../policy_tag_manager/async_client.py | 1300 +++ .../services/policy_tag_manager/client.py | 1503 +++ .../services/policy_tag_manager/pagers.py | 262 + .../policy_tag_manager/transports/__init__.py | 33 + .../policy_tag_manager/transports/base.py | 317 + .../policy_tag_manager/transports/grpc.py | 587 ++ .../transports/grpc_asyncio.py | 591 ++ .../__init__.py | 22 + .../async_client.py | 372 + .../client.py | 572 ++ .../transports/__init__.py | 33 + .../transports/base.py | 175 + .../transports/grpc.py | 335 + .../transports/grpc_asyncio.py | 339 + .../cloud/datacatalog_v1/types/__init__.py | 205 + .../cloud/datacatalog_v1/types/bigquery.py | 115 + .../cloud/datacatalog_v1/types/common.py | 37 + .../cloud/datacatalog_v1/types/data_source.py | 56 + .../cloud/datacatalog_v1/types/datacatalog.py | 1578 ++++ .../datacatalog_v1/types/gcs_fileset_spec.py | 115 + .../datacatalog_v1/types/policytagmanager.py | 495 + .../types/policytagmanagerserialization.py | 281 + .../cloud/datacatalog_v1/types/schema.py | 99 + .../cloud/datacatalog_v1/types/search.py | 164 + .../cloud/datacatalog_v1/types/table_spec.py | 161 + .../google/cloud/datacatalog_v1/types/tags.py | 458 + .../cloud/datacatalog_v1/types/timestamps.py | 67 + .../cloud/datacatalog_v1/types/usage.py | 103 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../scripts/fixup_datacatalog_v1_keywords.py | 216 + owl-bot-staging/v1/setup.py | 55 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/datacatalog_v1/__init__.py | 16 + .../gapic/datacatalog_v1/test_data_catalog.py | 8365 +++++++++++++++++ .../datacatalog_v1/test_policy_tag_manager.py | 4247 +++++++++ .../test_policy_tag_manager_serialization.py | 1379 +++ owl-bot-staging/v1beta1/.coveragerc | 17 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 + .../docs/datacatalog_v1beta1/data_catalog.rst | 10 + .../policy_tag_manager.rst | 10 + .../policy_tag_manager_serialization.rst | 6 + .../docs/datacatalog_v1beta1/services.rst | 8 + .../docs/datacatalog_v1beta1/types.rst | 7 + owl-bot-staging/v1beta1/docs/index.rst | 7 + .../google/cloud/datacatalog/__init__.py | 171 + .../v1beta1/google/cloud/datacatalog/py.typed | 2 + .../cloud/datacatalog_v1beta1/__init__.py | 172 + .../datacatalog_v1beta1/gapic_metadata.json | 471 + .../google/cloud/datacatalog_v1beta1/py.typed | 2 + .../datacatalog_v1beta1/services/__init__.py | 15 + .../services/data_catalog/__init__.py | 22 + .../services/data_catalog/async_client.py | 2878 ++++++ .../services/data_catalog/client.py | 3039 ++++++ .../services/data_catalog/pagers.py | 508 + .../data_catalog/transports/__init__.py | 33 + .../services/data_catalog/transports/base.py | 584 ++ .../services/data_catalog/transports/grpc.py | 1079 +++ .../data_catalog/transports/grpc_asyncio.py | 1083 +++ .../services/policy_tag_manager/__init__.py | 22 + .../policy_tag_manager/async_client.py | 1263 +++ .../services/policy_tag_manager/client.py | 1466 +++ .../services/policy_tag_manager/pagers.py | 262 + .../policy_tag_manager/transports/__init__.py | 33 + .../policy_tag_manager/transports/base.py | 317 + .../policy_tag_manager/transports/grpc.py | 575 ++ .../transports/grpc_asyncio.py | 579 ++ .../__init__.py | 22 + .../async_client.py | 288 + .../client.py | 487 + .../transports/__init__.py | 33 + .../transports/base.py | 160 + .../transports/grpc.py | 290 + .../transports/grpc_asyncio.py | 294 + .../datacatalog_v1beta1/types/__init__.py | 175 + .../cloud/datacatalog_v1beta1/types/common.py | 36 + .../datacatalog_v1beta1/types/datacatalog.py | 1225 +++ .../types/gcs_fileset_spec.py | 113 + .../types/policytagmanager.py | 449 + .../types/policytagmanagerserialization.py | 210 + .../cloud/datacatalog_v1beta1/types/schema.py | 89 + .../cloud/datacatalog_v1beta1/types/search.py | 88 + .../datacatalog_v1beta1/types/table_spec.py | 147 + .../cloud/datacatalog_v1beta1/types/tags.py | 384 + .../datacatalog_v1beta1/types/timestamps.py | 63 + owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 132 + .../fixup_datacatalog_v1beta1_keywords.py | 214 + owl-bot-staging/v1beta1/setup.py | 55 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/datacatalog_v1beta1/__init__.py | 16 + .../datacatalog_v1beta1/test_data_catalog.py | 8035 ++++++++++++++++ .../test_policy_tag_manager.py | 4233 +++++++++ .../test_policy_tag_manager_serialization.py | 1210 +++ 125 files changed, 69493 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/conf.py create mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst create mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst create mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst create mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py create mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.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_datacatalog_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/datacatalog_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst create mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst create mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst create mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..ac5fa2e9 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/datacatalog/__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..7344043d --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/datacatalog *.py +recursive-include google/cloud/datacatalog_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..8f53b244 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Datacatalog 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 Datacatalog API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..67b364b2 --- /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-datacatalog 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-datacatalog" +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-datacatalog-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-datacatalog.tex", + u"google-cloud-datacatalog 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-datacatalog", + u"Google Cloud Datacatalog 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-datacatalog", + u"google-cloud-datacatalog Documentation", + author, + "google-cloud-datacatalog", + "GAPIC library for Google Cloud Datacatalog 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/datacatalog_v1/data_catalog.rst b/owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst new file mode 100644 index 00000000..6141a1c7 --- /dev/null +++ b/owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst @@ -0,0 +1,10 @@ +DataCatalog +----------------------------- + +.. automodule:: google.cloud.datacatalog_v1.services.data_catalog + :members: + :inherited-members: + +.. automodule:: google.cloud.datacatalog_v1.services.data_catalog.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst new file mode 100644 index 00000000..03d2846f --- /dev/null +++ b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst @@ -0,0 +1,10 @@ +PolicyTagManager +---------------------------------- + +.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager + :members: + :inherited-members: + +.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst new file mode 100644 index 00000000..f7006d1b --- /dev/null +++ b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst @@ -0,0 +1,6 @@ +PolicyTagManagerSerialization +----------------------------------------------- + +.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager_serialization + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/services.rst b/owl-bot-staging/v1/docs/datacatalog_v1/services.rst new file mode 100644 index 00000000..a70d3132 --- /dev/null +++ b/owl-bot-staging/v1/docs/datacatalog_v1/services.rst @@ -0,0 +1,8 @@ +Services for Google Cloud Datacatalog v1 API +============================================ +.. toctree:: + :maxdepth: 2 + + data_catalog + policy_tag_manager + policy_tag_manager_serialization diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/types.rst b/owl-bot-staging/v1/docs/datacatalog_v1/types.rst new file mode 100644 index 00000000..a27783ee --- /dev/null +++ b/owl-bot-staging/v1/docs/datacatalog_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Datacatalog v1 API +========================================= + +.. automodule:: google.cloud.datacatalog_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..7af52885 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + datacatalog_v1/services + datacatalog_v1/types diff --git a/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py new file mode 100644 index 00000000..41e4328e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py @@ -0,0 +1,195 @@ +# -*- 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.datacatalog_v1.services.data_catalog.client import DataCatalogClient +from google.cloud.datacatalog_v1.services.data_catalog.async_client import DataCatalogAsyncClient +from google.cloud.datacatalog_v1.services.policy_tag_manager.client import PolicyTagManagerClient +from google.cloud.datacatalog_v1.services.policy_tag_manager.async_client import PolicyTagManagerAsyncClient +from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.client import PolicyTagManagerSerializationClient +from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.async_client import PolicyTagManagerSerializationAsyncClient + +from google.cloud.datacatalog_v1.types.bigquery import BigQueryConnectionSpec +from google.cloud.datacatalog_v1.types.bigquery import BigQueryRoutineSpec +from google.cloud.datacatalog_v1.types.bigquery import CloudSqlBigQueryConnectionSpec +from google.cloud.datacatalog_v1.types.common import IntegratedSystem +from google.cloud.datacatalog_v1.types.data_source import DataSource +from google.cloud.datacatalog_v1.types.datacatalog import CreateEntryGroupRequest +from google.cloud.datacatalog_v1.types.datacatalog import CreateEntryRequest +from google.cloud.datacatalog_v1.types.datacatalog import CreateTagRequest +from google.cloud.datacatalog_v1.types.datacatalog import CreateTagTemplateFieldRequest +from google.cloud.datacatalog_v1.types.datacatalog import CreateTagTemplateRequest +from google.cloud.datacatalog_v1.types.datacatalog import DatabaseTableSpec +from google.cloud.datacatalog_v1.types.datacatalog import DataSourceConnectionSpec +from google.cloud.datacatalog_v1.types.datacatalog import DeleteEntryGroupRequest +from google.cloud.datacatalog_v1.types.datacatalog import DeleteEntryRequest +from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagRequest +from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagTemplateFieldRequest +from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagTemplateRequest +from google.cloud.datacatalog_v1.types.datacatalog import Entry +from google.cloud.datacatalog_v1.types.datacatalog import EntryGroup +from google.cloud.datacatalog_v1.types.datacatalog import GetEntryGroupRequest +from google.cloud.datacatalog_v1.types.datacatalog import GetEntryRequest +from google.cloud.datacatalog_v1.types.datacatalog import GetTagTemplateRequest +from google.cloud.datacatalog_v1.types.datacatalog import ListEntriesRequest +from google.cloud.datacatalog_v1.types.datacatalog import ListEntriesResponse +from google.cloud.datacatalog_v1.types.datacatalog import ListEntryGroupsRequest +from google.cloud.datacatalog_v1.types.datacatalog import ListEntryGroupsResponse +from google.cloud.datacatalog_v1.types.datacatalog import ListTagsRequest +from google.cloud.datacatalog_v1.types.datacatalog import ListTagsResponse +from google.cloud.datacatalog_v1.types.datacatalog import LookupEntryRequest +from google.cloud.datacatalog_v1.types.datacatalog import RenameTagTemplateFieldEnumValueRequest +from google.cloud.datacatalog_v1.types.datacatalog import RenameTagTemplateFieldRequest +from google.cloud.datacatalog_v1.types.datacatalog import RoutineSpec +from google.cloud.datacatalog_v1.types.datacatalog import SearchCatalogRequest +from google.cloud.datacatalog_v1.types.datacatalog import SearchCatalogResponse +from google.cloud.datacatalog_v1.types.datacatalog import UpdateEntryGroupRequest +from google.cloud.datacatalog_v1.types.datacatalog import UpdateEntryRequest +from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagRequest +from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagTemplateFieldRequest +from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagTemplateRequest +from google.cloud.datacatalog_v1.types.datacatalog import EntryType +from google.cloud.datacatalog_v1.types.gcs_fileset_spec import GcsFilesetSpec +from google.cloud.datacatalog_v1.types.gcs_fileset_spec import GcsFileSpec +from google.cloud.datacatalog_v1.types.policytagmanager import CreatePolicyTagRequest +from google.cloud.datacatalog_v1.types.policytagmanager import CreateTaxonomyRequest +from google.cloud.datacatalog_v1.types.policytagmanager import DeletePolicyTagRequest +from google.cloud.datacatalog_v1.types.policytagmanager import DeleteTaxonomyRequest +from google.cloud.datacatalog_v1.types.policytagmanager import GetPolicyTagRequest +from google.cloud.datacatalog_v1.types.policytagmanager import GetTaxonomyRequest +from google.cloud.datacatalog_v1.types.policytagmanager import ListPolicyTagsRequest +from google.cloud.datacatalog_v1.types.policytagmanager import ListPolicyTagsResponse +from google.cloud.datacatalog_v1.types.policytagmanager import ListTaxonomiesRequest +from google.cloud.datacatalog_v1.types.policytagmanager import ListTaxonomiesResponse +from google.cloud.datacatalog_v1.types.policytagmanager import PolicyTag +from google.cloud.datacatalog_v1.types.policytagmanager import Taxonomy +from google.cloud.datacatalog_v1.types.policytagmanager import UpdatePolicyTagRequest +from google.cloud.datacatalog_v1.types.policytagmanager import UpdateTaxonomyRequest +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import CrossRegionalSource +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ExportTaxonomiesRequest +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ExportTaxonomiesResponse +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ImportTaxonomiesRequest +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ImportTaxonomiesResponse +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import InlineSource +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ReplaceTaxonomyRequest +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import SerializedPolicyTag +from google.cloud.datacatalog_v1.types.policytagmanagerserialization import SerializedTaxonomy +from google.cloud.datacatalog_v1.types.schema import ColumnSchema +from google.cloud.datacatalog_v1.types.schema import Schema +from google.cloud.datacatalog_v1.types.search import SearchCatalogResult +from google.cloud.datacatalog_v1.types.search import SearchResultType +from google.cloud.datacatalog_v1.types.table_spec import BigQueryDateShardedSpec +from google.cloud.datacatalog_v1.types.table_spec import BigQueryTableSpec +from google.cloud.datacatalog_v1.types.table_spec import TableSpec +from google.cloud.datacatalog_v1.types.table_spec import ViewSpec +from google.cloud.datacatalog_v1.types.table_spec import TableSourceType +from google.cloud.datacatalog_v1.types.tags import FieldType +from google.cloud.datacatalog_v1.types.tags import Tag +from google.cloud.datacatalog_v1.types.tags import TagField +from google.cloud.datacatalog_v1.types.tags import TagTemplate +from google.cloud.datacatalog_v1.types.tags import TagTemplateField +from google.cloud.datacatalog_v1.types.timestamps import SystemTimestamps +from google.cloud.datacatalog_v1.types.usage import UsageSignal +from google.cloud.datacatalog_v1.types.usage import UsageStats + +__all__ = ('DataCatalogClient', + 'DataCatalogAsyncClient', + 'PolicyTagManagerClient', + 'PolicyTagManagerAsyncClient', + 'PolicyTagManagerSerializationClient', + 'PolicyTagManagerSerializationAsyncClient', + 'BigQueryConnectionSpec', + 'BigQueryRoutineSpec', + 'CloudSqlBigQueryConnectionSpec', + 'IntegratedSystem', + 'DataSource', + 'CreateEntryGroupRequest', + 'CreateEntryRequest', + 'CreateTagRequest', + 'CreateTagTemplateFieldRequest', + 'CreateTagTemplateRequest', + 'DatabaseTableSpec', + 'DataSourceConnectionSpec', + 'DeleteEntryGroupRequest', + 'DeleteEntryRequest', + 'DeleteTagRequest', + 'DeleteTagTemplateFieldRequest', + 'DeleteTagTemplateRequest', + 'Entry', + 'EntryGroup', + 'GetEntryGroupRequest', + 'GetEntryRequest', + 'GetTagTemplateRequest', + 'ListEntriesRequest', + 'ListEntriesResponse', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'ListTagsRequest', + 'ListTagsResponse', + 'LookupEntryRequest', + 'RenameTagTemplateFieldEnumValueRequest', + 'RenameTagTemplateFieldRequest', + 'RoutineSpec', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'UpdateEntryGroupRequest', + 'UpdateEntryRequest', + 'UpdateTagRequest', + 'UpdateTagTemplateFieldRequest', + 'UpdateTagTemplateRequest', + 'EntryType', + 'GcsFilesetSpec', + 'GcsFileSpec', + 'CreatePolicyTagRequest', + 'CreateTaxonomyRequest', + 'DeletePolicyTagRequest', + 'DeleteTaxonomyRequest', + 'GetPolicyTagRequest', + 'GetTaxonomyRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'PolicyTag', + 'Taxonomy', + 'UpdatePolicyTagRequest', + 'UpdateTaxonomyRequest', + 'CrossRegionalSource', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + 'ImportTaxonomiesRequest', + 'ImportTaxonomiesResponse', + 'InlineSource', + 'ReplaceTaxonomyRequest', + 'SerializedPolicyTag', + 'SerializedTaxonomy', + 'ColumnSchema', + 'Schema', + 'SearchCatalogResult', + 'SearchResultType', + 'BigQueryDateShardedSpec', + 'BigQueryTableSpec', + 'TableSpec', + 'ViewSpec', + 'TableSourceType', + 'FieldType', + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'SystemTimestamps', + 'UsageSignal', + 'UsageStats', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog/py.typed b/owl-bot-staging/v1/google/cloud/datacatalog/py.typed new file mode 100644 index 00000000..bb4088a3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py new file mode 100644 index 00000000..bd45c6c1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py @@ -0,0 +1,196 @@ +# -*- 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_catalog import DataCatalogClient +from .services.data_catalog import DataCatalogAsyncClient +from .services.policy_tag_manager import PolicyTagManagerClient +from .services.policy_tag_manager import PolicyTagManagerAsyncClient +from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient +from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient + +from .types.bigquery import BigQueryConnectionSpec +from .types.bigquery import BigQueryRoutineSpec +from .types.bigquery import CloudSqlBigQueryConnectionSpec +from .types.common import IntegratedSystem +from .types.data_source import DataSource +from .types.datacatalog import CreateEntryGroupRequest +from .types.datacatalog import CreateEntryRequest +from .types.datacatalog import CreateTagRequest +from .types.datacatalog import CreateTagTemplateFieldRequest +from .types.datacatalog import CreateTagTemplateRequest +from .types.datacatalog import DatabaseTableSpec +from .types.datacatalog import DataSourceConnectionSpec +from .types.datacatalog import DeleteEntryGroupRequest +from .types.datacatalog import DeleteEntryRequest +from .types.datacatalog import DeleteTagRequest +from .types.datacatalog import DeleteTagTemplateFieldRequest +from .types.datacatalog import DeleteTagTemplateRequest +from .types.datacatalog import Entry +from .types.datacatalog import EntryGroup +from .types.datacatalog import GetEntryGroupRequest +from .types.datacatalog import GetEntryRequest +from .types.datacatalog import GetTagTemplateRequest +from .types.datacatalog import ListEntriesRequest +from .types.datacatalog import ListEntriesResponse +from .types.datacatalog import ListEntryGroupsRequest +from .types.datacatalog import ListEntryGroupsResponse +from .types.datacatalog import ListTagsRequest +from .types.datacatalog import ListTagsResponse +from .types.datacatalog import LookupEntryRequest +from .types.datacatalog import RenameTagTemplateFieldEnumValueRequest +from .types.datacatalog import RenameTagTemplateFieldRequest +from .types.datacatalog import RoutineSpec +from .types.datacatalog import SearchCatalogRequest +from .types.datacatalog import SearchCatalogResponse +from .types.datacatalog import UpdateEntryGroupRequest +from .types.datacatalog import UpdateEntryRequest +from .types.datacatalog import UpdateTagRequest +from .types.datacatalog import UpdateTagTemplateFieldRequest +from .types.datacatalog import UpdateTagTemplateRequest +from .types.datacatalog import EntryType +from .types.gcs_fileset_spec import GcsFilesetSpec +from .types.gcs_fileset_spec import GcsFileSpec +from .types.policytagmanager import CreatePolicyTagRequest +from .types.policytagmanager import CreateTaxonomyRequest +from .types.policytagmanager import DeletePolicyTagRequest +from .types.policytagmanager import DeleteTaxonomyRequest +from .types.policytagmanager import GetPolicyTagRequest +from .types.policytagmanager import GetTaxonomyRequest +from .types.policytagmanager import ListPolicyTagsRequest +from .types.policytagmanager import ListPolicyTagsResponse +from .types.policytagmanager import ListTaxonomiesRequest +from .types.policytagmanager import ListTaxonomiesResponse +from .types.policytagmanager import PolicyTag +from .types.policytagmanager import Taxonomy +from .types.policytagmanager import UpdatePolicyTagRequest +from .types.policytagmanager import UpdateTaxonomyRequest +from .types.policytagmanagerserialization import CrossRegionalSource +from .types.policytagmanagerserialization import ExportTaxonomiesRequest +from .types.policytagmanagerserialization import ExportTaxonomiesResponse +from .types.policytagmanagerserialization import ImportTaxonomiesRequest +from .types.policytagmanagerserialization import ImportTaxonomiesResponse +from .types.policytagmanagerserialization import InlineSource +from .types.policytagmanagerserialization import ReplaceTaxonomyRequest +from .types.policytagmanagerserialization import SerializedPolicyTag +from .types.policytagmanagerserialization import SerializedTaxonomy +from .types.schema import ColumnSchema +from .types.schema import Schema +from .types.search import SearchCatalogResult +from .types.search import SearchResultType +from .types.table_spec import BigQueryDateShardedSpec +from .types.table_spec import BigQueryTableSpec +from .types.table_spec import TableSpec +from .types.table_spec import ViewSpec +from .types.table_spec import TableSourceType +from .types.tags import FieldType +from .types.tags import Tag +from .types.tags import TagField +from .types.tags import TagTemplate +from .types.tags import TagTemplateField +from .types.timestamps import SystemTimestamps +from .types.usage import UsageSignal +from .types.usage import UsageStats + +__all__ = ( + 'DataCatalogAsyncClient', + 'PolicyTagManagerAsyncClient', + 'PolicyTagManagerSerializationAsyncClient', +'BigQueryConnectionSpec', +'BigQueryDateShardedSpec', +'BigQueryRoutineSpec', +'BigQueryTableSpec', +'CloudSqlBigQueryConnectionSpec', +'ColumnSchema', +'CreateEntryGroupRequest', +'CreateEntryRequest', +'CreatePolicyTagRequest', +'CreateTagRequest', +'CreateTagTemplateFieldRequest', +'CreateTagTemplateRequest', +'CreateTaxonomyRequest', +'CrossRegionalSource', +'DataCatalogClient', +'DataSource', +'DataSourceConnectionSpec', +'DatabaseTableSpec', +'DeleteEntryGroupRequest', +'DeleteEntryRequest', +'DeletePolicyTagRequest', +'DeleteTagRequest', +'DeleteTagTemplateFieldRequest', +'DeleteTagTemplateRequest', +'DeleteTaxonomyRequest', +'Entry', +'EntryGroup', +'EntryType', +'ExportTaxonomiesRequest', +'ExportTaxonomiesResponse', +'FieldType', +'GcsFileSpec', +'GcsFilesetSpec', +'GetEntryGroupRequest', +'GetEntryRequest', +'GetPolicyTagRequest', +'GetTagTemplateRequest', +'GetTaxonomyRequest', +'ImportTaxonomiesRequest', +'ImportTaxonomiesResponse', +'InlineSource', +'IntegratedSystem', +'ListEntriesRequest', +'ListEntriesResponse', +'ListEntryGroupsRequest', +'ListEntryGroupsResponse', +'ListPolicyTagsRequest', +'ListPolicyTagsResponse', +'ListTagsRequest', +'ListTagsResponse', +'ListTaxonomiesRequest', +'ListTaxonomiesResponse', +'LookupEntryRequest', +'PolicyTag', +'PolicyTagManagerClient', +'PolicyTagManagerSerializationClient', +'RenameTagTemplateFieldEnumValueRequest', +'RenameTagTemplateFieldRequest', +'ReplaceTaxonomyRequest', +'RoutineSpec', +'Schema', +'SearchCatalogRequest', +'SearchCatalogResponse', +'SearchCatalogResult', +'SearchResultType', +'SerializedPolicyTag', +'SerializedTaxonomy', +'SystemTimestamps', +'TableSourceType', +'TableSpec', +'Tag', +'TagField', +'TagTemplate', +'TagTemplateField', +'Taxonomy', +'UpdateEntryGroupRequest', +'UpdateEntryRequest', +'UpdatePolicyTagRequest', +'UpdateTagRequest', +'UpdateTagTemplateFieldRequest', +'UpdateTagTemplateRequest', +'UpdateTaxonomyRequest', +'UsageSignal', +'UsageStats', +'ViewSpec', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json new file mode 100644 index 00000000..99e0398a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json @@ -0,0 +1,491 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.datacatalog_v1", + "protoPackage": "google.cloud.datacatalog.v1", + "schema": "1.0", + "services": { + "DataCatalog": { + "clients": { + "grpc": { + "libraryClient": "DataCatalogClient", + "rpcs": { + "CreateEntry": { + "methods": [ + "create_entry" + ] + }, + "CreateEntryGroup": { + "methods": [ + "create_entry_group" + ] + }, + "CreateTag": { + "methods": [ + "create_tag" + ] + }, + "CreateTagTemplate": { + "methods": [ + "create_tag_template" + ] + }, + "CreateTagTemplateField": { + "methods": [ + "create_tag_template_field" + ] + }, + "DeleteEntry": { + "methods": [ + "delete_entry" + ] + }, + "DeleteEntryGroup": { + "methods": [ + "delete_entry_group" + ] + }, + "DeleteTag": { + "methods": [ + "delete_tag" + ] + }, + "DeleteTagTemplate": { + "methods": [ + "delete_tag_template" + ] + }, + "DeleteTagTemplateField": { + "methods": [ + "delete_tag_template_field" + ] + }, + "GetEntry": { + "methods": [ + "get_entry" + ] + }, + "GetEntryGroup": { + "methods": [ + "get_entry_group" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagTemplate": { + "methods": [ + "get_tag_template" + ] + }, + "ListEntries": { + "methods": [ + "list_entries" + ] + }, + "ListEntryGroups": { + "methods": [ + "list_entry_groups" + ] + }, + "ListTags": { + "methods": [ + "list_tags" + ] + }, + "LookupEntry": { + "methods": [ + "lookup_entry" + ] + }, + "RenameTagTemplateField": { + "methods": [ + "rename_tag_template_field" + ] + }, + "RenameTagTemplateFieldEnumValue": { + "methods": [ + "rename_tag_template_field_enum_value" + ] + }, + "SearchCatalog": { + "methods": [ + "search_catalog" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEntry": { + "methods": [ + "update_entry" + ] + }, + "UpdateEntryGroup": { + "methods": [ + "update_entry_group" + ] + }, + "UpdateTag": { + "methods": [ + "update_tag" + ] + }, + "UpdateTagTemplate": { + "methods": [ + "update_tag_template" + ] + }, + "UpdateTagTemplateField": { + "methods": [ + "update_tag_template_field" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataCatalogAsyncClient", + "rpcs": { + "CreateEntry": { + "methods": [ + "create_entry" + ] + }, + "CreateEntryGroup": { + "methods": [ + "create_entry_group" + ] + }, + "CreateTag": { + "methods": [ + "create_tag" + ] + }, + "CreateTagTemplate": { + "methods": [ + "create_tag_template" + ] + }, + "CreateTagTemplateField": { + "methods": [ + "create_tag_template_field" + ] + }, + "DeleteEntry": { + "methods": [ + "delete_entry" + ] + }, + "DeleteEntryGroup": { + "methods": [ + "delete_entry_group" + ] + }, + "DeleteTag": { + "methods": [ + "delete_tag" + ] + }, + "DeleteTagTemplate": { + "methods": [ + "delete_tag_template" + ] + }, + "DeleteTagTemplateField": { + "methods": [ + "delete_tag_template_field" + ] + }, + "GetEntry": { + "methods": [ + "get_entry" + ] + }, + "GetEntryGroup": { + "methods": [ + "get_entry_group" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagTemplate": { + "methods": [ + "get_tag_template" + ] + }, + "ListEntries": { + "methods": [ + "list_entries" + ] + }, + "ListEntryGroups": { + "methods": [ + "list_entry_groups" + ] + }, + "ListTags": { + "methods": [ + "list_tags" + ] + }, + "LookupEntry": { + "methods": [ + "lookup_entry" + ] + }, + "RenameTagTemplateField": { + "methods": [ + "rename_tag_template_field" + ] + }, + "RenameTagTemplateFieldEnumValue": { + "methods": [ + "rename_tag_template_field_enum_value" + ] + }, + "SearchCatalog": { + "methods": [ + "search_catalog" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEntry": { + "methods": [ + "update_entry" + ] + }, + "UpdateEntryGroup": { + "methods": [ + "update_entry_group" + ] + }, + "UpdateTag": { + "methods": [ + "update_tag" + ] + }, + "UpdateTagTemplate": { + "methods": [ + "update_tag_template" + ] + }, + "UpdateTagTemplateField": { + "methods": [ + "update_tag_template_field" + ] + } + } + } + } + }, + "PolicyTagManager": { + "clients": { + "grpc": { + "libraryClient": "PolicyTagManagerClient", + "rpcs": { + "CreatePolicyTag": { + "methods": [ + "create_policy_tag" + ] + }, + "CreateTaxonomy": { + "methods": [ + "create_taxonomy" + ] + }, + "DeletePolicyTag": { + "methods": [ + "delete_policy_tag" + ] + }, + "DeleteTaxonomy": { + "methods": [ + "delete_taxonomy" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetPolicyTag": { + "methods": [ + "get_policy_tag" + ] + }, + "GetTaxonomy": { + "methods": [ + "get_taxonomy" + ] + }, + "ListPolicyTags": { + "methods": [ + "list_policy_tags" + ] + }, + "ListTaxonomies": { + "methods": [ + "list_taxonomies" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdatePolicyTag": { + "methods": [ + "update_policy_tag" + ] + }, + "UpdateTaxonomy": { + "methods": [ + "update_taxonomy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyTagManagerAsyncClient", + "rpcs": { + "CreatePolicyTag": { + "methods": [ + "create_policy_tag" + ] + }, + "CreateTaxonomy": { + "methods": [ + "create_taxonomy" + ] + }, + "DeletePolicyTag": { + "methods": [ + "delete_policy_tag" + ] + }, + "DeleteTaxonomy": { + "methods": [ + "delete_taxonomy" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetPolicyTag": { + "methods": [ + "get_policy_tag" + ] + }, + "GetTaxonomy": { + "methods": [ + "get_taxonomy" + ] + }, + "ListPolicyTags": { + "methods": [ + "list_policy_tags" + ] + }, + "ListTaxonomies": { + "methods": [ + "list_taxonomies" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdatePolicyTag": { + "methods": [ + "update_policy_tag" + ] + }, + "UpdateTaxonomy": { + "methods": [ + "update_taxonomy" + ] + } + } + } + } + }, + "PolicyTagManagerSerialization": { + "clients": { + "grpc": { + "libraryClient": "PolicyTagManagerSerializationClient", + "rpcs": { + "ExportTaxonomies": { + "methods": [ + "export_taxonomies" + ] + }, + "ImportTaxonomies": { + "methods": [ + "import_taxonomies" + ] + }, + "ReplaceTaxonomy": { + "methods": [ + "replace_taxonomy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyTagManagerSerializationAsyncClient", + "rpcs": { + "ExportTaxonomies": { + "methods": [ + "export_taxonomies" + ] + }, + "ImportTaxonomies": { + "methods": [ + "import_taxonomies" + ] + }, + "ReplaceTaxonomy": { + "methods": [ + "replace_taxonomy" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed b/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed new file mode 100644 index 00000000..bb4088a3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_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/datacatalog_v1/services/data_catalog/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__init__.py new file mode 100644 index 00000000..b45be1eb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__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 DataCatalogClient +from .async_client import DataCatalogAsyncClient + +__all__ = ( + 'DataCatalogClient', + 'DataCatalogAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py new file mode 100644 index 00000000..1555beb7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py @@ -0,0 +1,3009 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.services.data_catalog import pagers +from google.cloud.datacatalog_v1.types import common +from google.cloud.datacatalog_v1.types import data_source +from google.cloud.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1.types import schema +from google.cloud.datacatalog_v1.types import search +from google.cloud.datacatalog_v1.types import table_spec +from google.cloud.datacatalog_v1.types import tags +from google.cloud.datacatalog_v1.types import timestamps +from google.cloud.datacatalog_v1.types import usage +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport +from .client import DataCatalogClient + + +class DataCatalogAsyncClient: + """Data Catalog API service allows you to discover, understand, + and manage your data. + """ + + _client: DataCatalogClient + + DEFAULT_ENDPOINT = DataCatalogClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataCatalogClient.DEFAULT_MTLS_ENDPOINT + + entry_path = staticmethod(DataCatalogClient.entry_path) + parse_entry_path = staticmethod(DataCatalogClient.parse_entry_path) + entry_group_path = staticmethod(DataCatalogClient.entry_group_path) + parse_entry_group_path = staticmethod(DataCatalogClient.parse_entry_group_path) + tag_path = staticmethod(DataCatalogClient.tag_path) + parse_tag_path = staticmethod(DataCatalogClient.parse_tag_path) + tag_template_path = staticmethod(DataCatalogClient.tag_template_path) + parse_tag_template_path = staticmethod(DataCatalogClient.parse_tag_template_path) + tag_template_field_path = staticmethod(DataCatalogClient.tag_template_field_path) + parse_tag_template_field_path = staticmethod(DataCatalogClient.parse_tag_template_field_path) + tag_template_field_enum_value_path = staticmethod(DataCatalogClient.tag_template_field_enum_value_path) + parse_tag_template_field_enum_value_path = staticmethod(DataCatalogClient.parse_tag_template_field_enum_value_path) + common_billing_account_path = staticmethod(DataCatalogClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataCatalogClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataCatalogClient.common_folder_path) + parse_common_folder_path = staticmethod(DataCatalogClient.parse_common_folder_path) + common_organization_path = staticmethod(DataCatalogClient.common_organization_path) + parse_common_organization_path = staticmethod(DataCatalogClient.parse_common_organization_path) + common_project_path = staticmethod(DataCatalogClient.common_project_path) + parse_common_project_path = staticmethod(DataCatalogClient.parse_common_project_path) + common_location_path = staticmethod(DataCatalogClient.common_location_path) + parse_common_location_path = staticmethod(DataCatalogClient.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: + DataCatalogAsyncClient: The constructed client. + """ + return DataCatalogClient.from_service_account_info.__func__(DataCatalogAsyncClient, 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: + DataCatalogAsyncClient: The constructed client. + """ + return DataCatalogClient.from_service_account_file.__func__(DataCatalogAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DataCatalogTransport: + """Returns the transport used by the client instance. + + Returns: + DataCatalogTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataCatalogClient).get_transport_class, type(DataCatalogClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DataCatalogTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data catalog 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, ~.DataCatalogTransport]): 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 = DataCatalogClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search_catalog(self, + request: Union[datacatalog.SearchCatalogRequest, dict] = None, + *, + scope: datacatalog.SearchCatalogRequest.Scope = None, + query: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchCatalogAsyncPager: + r"""Searches Data Catalog for multiple resources like entries and + tags that match a query. + + This is a [Custom Method] + (https://cloud.google.com/apis/design/custom_methods) that + doesn't return all information on a resource, only its ID and + high level fields. To get more information, you can subsequently + call specific get methods. + + Note: Data Catalog search queries don't guarantee full recall. + Results that match your query might not be returned, even in + subsequent result pages. Additionally, returned (and not + returned) results can vary if you repeat search queries. + + For more information, see [Data Catalog search syntax] + (https://cloud.google.com/data-catalog/docs/how-to/search-reference). + + Args: + request (Union[google.cloud.datacatalog_v1.types.SearchCatalogRequest, dict]): + The request object. Request message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + scope (:class:`google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope`): + Required. The scope of this search request. + + The ``scope`` is invalid if ``include_org_ids``, + ``include_project_ids`` are empty AND + ``include_gcp_public_datasets`` is set to ``false``. In + this case, the request returns an error. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query string with a minimum of 3 + characters and specific syntax. For more information, + see `Data Catalog search + syntax `__. + + An empty query string returns all data assets (in the + specified scope) that you have access to. + + A query string can be a simple ``xyz`` or qualified by + predicates: + + - ``name:x`` + - ``column:y`` + - ``description:z`` + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.services.data_catalog.pagers.SearchCatalogAsyncPager: + Response message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + 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([scope, query]) + if request is 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 = datacatalog.SearchCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_catalog, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.SearchCatalogAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entry_group(self, + request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, + *, + parent: str = None, + entry_group_id: str = None, + entry_group: datacatalog.EntryGroup = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Creates an entry group. + + An entry group contains logically related entries together with + `Cloud Identity and Access + Management `__ policies. These + policies specify users who can create, edit, and view entries + within entry groups. + + Data Catalog automatically creates entry groups with names that + start with the ``@`` symbol for the following resources: + + - BigQuery entries (``@bigquery``) + - Pub/Sub topics (``@pubsub``) + - Dataproc Metastore services + (``@dataproc_metastore_{SERVICE_NAME_HASH}``) + + You can create your own entry groups for Cloud Storage fileset + entries and custom entries together with the corresponding IAM + policies. User-created entry groups can't contain the ``@`` + symbol, it is reserved for automatically created groups. + + Entry groups, like entries, can be searched. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateEntryGroupRequest, dict]): + The request object. Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. + parent (:class:`str`): + Required. The names of the project + and location that the new entry group + belongs to. Note: The entry group + itself and its child resources might not + be stored in the location specified in + its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group_id (:class:`str`): + Required. The ID of the entry group to create. + + The ID must contain only letters (a-z, A-Z), numbers + (0-9), underscores (_), and must start with a letter or + underscore. The maximum size is 64 bytes when encoded in + UTF-8. + + This corresponds to the ``entry_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group (:class:`google.cloud.datacatalog_v1.types.EntryGroup`): + The entry group to create. Defaults + to empty. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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, entry_group_id, entry_group]) + if request is 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 = datacatalog.CreateEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_group_id is not None: + request.entry_group_id = entry_group_id + if entry_group is not None: + request.entry_group = entry_group + + # 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_entry_group, + default_timeout=None, + client_info=DEFAULT_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_entry_group(self, + request: Union[datacatalog.GetEntryGroupRequest, dict] = None, + *, + name: str = None, + read_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Gets an entry group. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetEntryGroupRequest, dict]): + The request object. Request message for + [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. + name (:class:`str`): + Required. The name of the entry group + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + read_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to return. If empty or + omitted, all fields are returned. + + This corresponds to the ``read_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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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, read_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 = datacatalog.GetEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if read_mask is not None: + request.read_mask = read_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.get_entry_group, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_entry_group(self, + request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, + *, + entry_group: datacatalog.EntryGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Updates an entry group. + + You must enable the Data Catalog API in the project identified + by the ``entry_group.name`` parameter. For more information, see + `Data Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateEntryGroupRequest, dict]): + The request object. Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. + entry_group (:class:`google.cloud.datacatalog_v1.types.EntryGroup`): + Required. Updates for the entry group. The ``name`` + field must be set. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Names of fields whose values to + overwrite on an entry group. + If this parameter is absent or empty, + all modifiable fields are overwritten. + If such fields are non-required and + omitted in the request body, their + values are emptied. + + 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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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([entry_group, 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 = datacatalog.UpdateEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry_group is not None: + request.entry_group = entry_group + 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_entry_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry_group.name", request.entry_group.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entry_group(self, + request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an entry group. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteEntryGroupRequest, dict]): + The request object. Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. + name (:class:`str`): + Required. The name of the entry group + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = datacatalog.DeleteEntryGroupRequest(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_entry_group, + default_timeout=None, + client_info=DEFAULT_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_entry_groups(self, + request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntryGroupsAsyncPager: + r"""Lists entry groups. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListEntryGroupsRequest, dict]): + The request object. Request message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + parent (:class:`str`): + Required. The name of the location + that contains the entry groups to list. + Can be provided as a URL. + + 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.datacatalog_v1.services.data_catalog.pagers.ListEntryGroupsAsyncPager: + Response message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + + 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 = datacatalog.ListEntryGroupsRequest(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_entry_groups, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEntryGroupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entry(self, + request: Union[datacatalog.CreateEntryRequest, dict] = None, + *, + parent: str = None, + entry_id: str = None, + entry: datacatalog.Entry = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Creates an entry. + + You can create entries only with 'FILESET', 'CLUSTER', + 'DATA_STREAM', or custom types. Data Catalog automatically + creates entries with other types during metadata ingestion from + integrated systems. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + An entry group can have a maximum of 100,000 entries. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateEntryRequest, dict]): + The request object. Request message for + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. + parent (:class:`str`): + Required. The name of the entry group + this entry belongs to. + Note: The entry itself and its child + resources might not be stored in the + location specified in its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_id (:class:`str`): + Required. The ID of the entry to create. + + The ID must contain only letters (a-z, A-Z), numbers + (0-9), and underscores (_). The maximum size is 64 bytes + when encoded in UTF-8. + + This corresponds to the ``entry_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry (:class:`google.cloud.datacatalog_v1.types.Entry`): + Required. The entry to create. + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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, entry_id, entry]) + if request is 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 = datacatalog.CreateEntryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_id is not None: + request.entry_id = entry_id + if entry is not None: + request.entry = entry + + # 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_entry, + default_timeout=None, + client_info=DEFAULT_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_entry(self, + request: Union[datacatalog.UpdateEntryRequest, dict] = None, + *, + entry: datacatalog.Entry = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Updates an existing entry. + + You must enable the Data Catalog API in the project identified + by the ``entry.name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateEntryRequest, dict]): + The request object. Request message for + [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. + entry (:class:`google.cloud.datacatalog_v1.types.Entry`): + Required. Updates for the entry. The ``name`` field must + be set. + + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Names of fields whose values to overwrite on an entry. + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied. + + You can modify only the fields listed below. + + For entries with type ``DATA_STREAM``: + + - ``schema`` + + For entries with type ``FILESET``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + For entries with ``user_specified_type``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``user_specified_type`` + - ``user_specified_system`` + - ``linked_resource`` + - ``source_system_timestamps`` + + 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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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([entry, 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 = datacatalog.UpdateEntryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry is not None: + request.entry = entry + 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_entry, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry.name", request.entry.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entry(self, + request: Union[datacatalog.DeleteEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing entry. + + You can delete only the entries created by the + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] + method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteEntryRequest, dict]): + The request object. Request message for + [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. + name (:class:`str`): + Required. The name of the entry to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = datacatalog.DeleteEntryRequest(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_entry, + default_timeout=None, + client_info=DEFAULT_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_entry(self, + request: Union[datacatalog.GetEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetEntryRequest, dict]): + The request object. Request message for + [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. + name (:class:`str`): + Required. The name of the entry to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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 = datacatalog.GetEntryRequest(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_entry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def lookup_entry(self, + request: Union[datacatalog.LookupEntryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry by its target resource name. + The resource name comes from the source Google Cloud + Platform service. + + Args: + request (Union[google.cloud.datacatalog_v1.types.LookupEntryRequest, dict]): + The request object. Request message for + [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # Create or coerce a protobuf request object. + request = datacatalog.LookupEntryRequest(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.lookup_entry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_entries(self, + request: Union[datacatalog.ListEntriesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntriesAsyncPager: + r"""Lists entries. + + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): + The request object. Request message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + parent (:class:`str`): + Required. The name of the entry group + that contains the entries to list. + Can be provided in URL format. + + 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.datacatalog_v1.services.data_catalog.pagers.ListEntriesAsyncPager: + Response message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + + 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 = datacatalog.ListEntriesRequest(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_entries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEntriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tag_template(self, + request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, + *, + parent: str = None, + tag_template_id: str = None, + tag_template: tags.TagTemplate = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Creates a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateRequest, dict]): + The request object. Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. + parent (:class:`str`): + Required. The name of the project and the template + location + `region `__. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_id (:class:`str`): + Required. The ID of the tag template to create. + + The ID must contain only lowercase letters (a-z), + numbers (0-9), or underscores (_), and must start with a + letter or underscore. The maximum size is 64 bytes when + encoded in UTF-8. + + This corresponds to the ``tag_template_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template (:class:`google.cloud.datacatalog_v1.types.TagTemplate`): + Required. The tag template to create. + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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, tag_template_id, tag_template]) + if request is 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 = datacatalog.CreateTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_id is not None: + request.tag_template_id = tag_template_id + if tag_template is not None: + request.tag_template = tag_template + + # 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_tag_template, + default_timeout=None, + client_info=DEFAULT_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_tag_template(self, + request: Union[datacatalog.GetTagTemplateRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Gets a tag template. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetTagTemplateRequest, dict]): + The request object. Request message for + [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. + name (:class:`str`): + Required. The name of the tag + template to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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 = datacatalog.GetTagTemplateRequest(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_tag_template, + default_timeout=None, + client_info=DEFAULT_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 update_tag_template(self, + request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, + *, + tag_template: tags.TagTemplate = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Updates a tag template. + + You can't update template fields with this method. These fields + are separate resources with their own create, update, and delete + methods. + + You must enable the Data Catalog API in the project identified + by the ``tag_template.name`` parameter. For more information, + see `Data Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateRequest, dict]): + The request object. Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. + tag_template (:class:`google.cloud.datacatalog_v1.types.TagTemplate`): + Required. The template to update. The ``name`` field + must be set. + + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Names of fields whose values to overwrite on a tag + template. Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied. + + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. + + 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.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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([tag_template, 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 = datacatalog.UpdateTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_template is not None: + request.tag_template = tag_template + 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_tag_template, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_template.name", request.tag_template.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tag_template(self, + request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag template and all tags that use it. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateRequest, dict]): + The request object. Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. + name (:class:`str`): + Required. The name of the tag + template to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Required. If true, deletes all tags that use this + template. + + Currently, ``true`` is the only supported value. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 = datacatalog.DeleteTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # 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_tag_template, + default_timeout=None, + client_info=DEFAULT_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 create_tag_template_field(self, + request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, + *, + parent: str = None, + tag_template_field_id: str = None, + tag_template_field: tags.TagTemplateField = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Creates a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateFieldRequest, dict]): + The request object. Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. + parent (:class:`str`): + Required. The name of the project and the template + location + `region `__. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field_id (:class:`str`): + Required. The ID of the tag template field to create. + + Note: Adding a required field to an existing template is + *not* allowed. + + Field IDs can contain letters (both uppercase and + lowercase), numbers (0-9), underscores (_) and dashes + (-). Field IDs must be at least 1 character long and at + most 128 characters long. Field IDs must also be unique + within their template. + + This corresponds to the ``tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (:class:`google.cloud.datacatalog_v1.types.TagTemplateField`): + Required. The tag template field to + create. + + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field_id, tag_template_field]) + if request is 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 = datacatalog.CreateTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_field_id is not None: + request.tag_template_field_id = tag_template_field_id + if tag_template_field is not None: + request.tag_template_field = tag_template_field + + # 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_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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_tag_template_field(self, + request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + tag_template_field: tags.TagTemplateField = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Updates a field in a tag template. + + You can't update the field type with this method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateFieldRequest, dict]): + The request object. Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. + name (:class:`str`): + Required. The name of the tag + template field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (:class:`google.cloud.datacatalog_v1.types.TagTemplateField`): + Required. The template to update. + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Names of fields whose values to overwrite on + an individual field of a tag template. The following + fields are modifiable: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied with one exception: when updating an enum type, + the provided values are merged with the existing values. + Therefore, enum values can only be added, existing enum + values cannot be deleted or renamed. + + Additionally, updating a template field from optional to + required is *not* allowed. + + 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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field, 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 = datacatalog.UpdateTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if tag_template_field is not None: + request.tag_template_field = tag_template_field + 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_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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 rename_tag_template_field(self, + request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + new_tag_template_field_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Args: + request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldRequest, dict]): + The request object. Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. + name (:class:`str`): + Required. The name of the tag + template field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_tag_template_field_id (:class:`str`): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + + This corresponds to the ``new_tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_tag_template_field_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datacatalog.RenameTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_tag_template_field_id is not None: + request.new_tag_template_field_id = new_tag_template_field_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.rename_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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 rename_tag_template_field_enum_value(self, + request: Union[datacatalog.RenameTagTemplateFieldEnumValueRequest, dict] = None, + *, + name: str = None, + new_enum_value_display_name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames an enum value in a tag template. + Within a single enum field, enum values must be unique. + + Args: + request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldEnumValueRequest, dict]): + The request object. Request message for + [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. + name (:class:`str`): + Required. The name of the enum field + value. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_enum_value_display_name (:class:`str`): + Required. The new display name of the enum value. For + example, ``my_new_enum_value``. + + This corresponds to the ``new_enum_value_display_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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_enum_value_display_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 = datacatalog.RenameTagTemplateFieldEnumValueRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_enum_value_display_name is not None: + request.new_enum_value_display_name = new_enum_value_display_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.rename_tag_template_field_enum_value, + default_timeout=None, + client_info=DEFAULT_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_tag_template_field(self, + request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a field in a tag template and all uses of this field + from the tags based on this template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateFieldRequest, dict]): + The request object. Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. + name (:class:`str`): + Required. The name of the tag + template field to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Required. If true, deletes this field from any tags that + use it. + + Currently, ``true`` is the only supported value. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 = datacatalog.DeleteTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # 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_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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 create_tag(self, + request: Union[datacatalog.CreateTagRequest, dict] = None, + *, + parent: str = None, + tag: tags.Tag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Creates a tag and assigns it to: + + - An [Entry][google.cloud.datacatalog.v1.Entry] if the method + name is + ``projects.locations.entryGroups.entries.tags.create``. + - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the + method name is + ``projects.locations.entryGroups.tags.create``. + + Note: The project identified by the ``parent`` parameter for the + [tag] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) + and the [tag template] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) + used to create the tag must be in the same organization. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagRequest, dict]): + The request object. Request message for + [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. + parent (:class:`str`): + Required. The name of the resource to + attach this tag to. + Tags can be attached to entries or entry + groups. An entry can have up to 1000 + attached tags. + + Note: The tag and its child resources + might not be stored in the location + specified in its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag (:class:`google.cloud.datacatalog_v1.types.Tag`): + Required. The tag to create. + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Tag: + Tags contain custom metadata and are attached to Data Catalog resources. Tags + conform with the specification of their tag template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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, tag]) + if request is 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 = datacatalog.CreateTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag is not None: + request.tag = tag + + # 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_tag, + default_timeout=None, + client_info=DEFAULT_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_tag(self, + request: Union[datacatalog.UpdateTagRequest, dict] = None, + *, + tag: tags.Tag = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Updates an existing tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagRequest, dict]): + The request object. Request message for + [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. + tag (:class:`google.cloud.datacatalog_v1.types.Tag`): + Required. The updated tag. The "name" + field must be set. + + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Names of fields whose values to overwrite on a tag. + Currently, a tag has the only modifiable field with the + name ``fields``. + + In general, if this parameter is absent or empty, all + modifiable fields are overwritten. If such fields are + non-required and omitted in the request body, their + values are emptied. + + 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.datacatalog_v1.types.Tag: + Tags contain custom metadata and are attached to Data Catalog resources. Tags + conform with the specification of their tag template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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([tag, 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 = datacatalog.UpdateTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag is not None: + request.tag = tag + 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_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag.name", request.tag.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tag(self, + request: Union[datacatalog.DeleteTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagRequest, dict]): + The request object. Request message for + [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. + name (:class:`str`): + Required. The name of the tag to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = datacatalog.DeleteTagRequest(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_tag, + default_timeout=None, + client_info=DEFAULT_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_tags(self, + request: Union[datacatalog.ListTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTagsAsyncPager: + r"""Lists tags assigned to an + [Entry][google.cloud.datacatalog.v1.Entry]. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListTagsRequest, dict]): + The request object. Request message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + parent (:class:`str`): + Required. The name of the Data Catalog resource to list + the tags of. + + The resource can be an + [Entry][google.cloud.datacatalog.v1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] + (without ``/entries/{entries}`` at the end). + + 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.datacatalog_v1.services.data_catalog.pagers.ListTagsAsyncPager: + Response message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + + 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 = datacatalog.ListTagsRequest(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_tags, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets an access control policy for a resource. Replaces any + existing policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method sets policies only within Data Catalog and + can't be used to manage policies in BigQuery, Pub/Sub, Dataproc + Metastore, and any external Google Cloud Platform resources + synced with the Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. + + May return: + + - A\ ``NOT_FOUND`` error if the resource doesn't exist or you + don't have the permission to view it. + - An empty policy if the resource exists but doesn't have a set + policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method doesn't get policies from Google Cloud + Platform resources ingested into Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # 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_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Gets your permissions on a resource. + Returns an empty set of permissions if the resource + doesn't exist. + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method gets policies only within Data Catalog + and can't be used to get policies from BigQuery, + Pub/Sub, Dataproc Metastore, and any external Google + Cloud Platform resources ingested into Data Catalog. + No Google IAM permissions are required to call this + method. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataCatalogAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py new file mode 100644 index 00000000..25b6af01 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py @@ -0,0 +1,3201 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.services.data_catalog import pagers +from google.cloud.datacatalog_v1.types import common +from google.cloud.datacatalog_v1.types import data_source +from google.cloud.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1.types import schema +from google.cloud.datacatalog_v1.types import search +from google.cloud.datacatalog_v1.types import table_spec +from google.cloud.datacatalog_v1.types import tags +from google.cloud.datacatalog_v1.types import timestamps +from google.cloud.datacatalog_v1.types import usage +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataCatalogGrpcTransport +from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport + + +class DataCatalogClientMeta(type): + """Metaclass for the DataCatalog 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[DataCatalogTransport]] + _transport_registry["grpc"] = DataCatalogGrpcTransport + _transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DataCatalogTransport]: + """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 DataCatalogClient(metaclass=DataCatalogClientMeta): + """Data Catalog API service allows you to discover, understand, + and manage your data. + """ + + @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 = "datacatalog.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: + DataCatalogClient: 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: + DataCatalogClient: 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) -> DataCatalogTransport: + """Returns the transport used by the client instance. + + Returns: + DataCatalogTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entry_path(project: str,location: str,entry_group: str,entry: str,) -> str: + """Returns a fully-qualified entry string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) + + @staticmethod + def parse_entry_path(path: str) -> Dict[str,str]: + """Parses a entry path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def entry_group_path(project: str,location: str,entry_group: str,) -> str: + """Returns a fully-qualified entry_group string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) + + @staticmethod + def parse_entry_group_path(path: str) -> Dict[str,str]: + """Parses a entry_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_path(project: str,location: str,entry_group: str,entry: str,tag: str,) -> str: + """Returns a fully-qualified tag string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) + + @staticmethod + def parse_tag_path(path: str) -> Dict[str,str]: + """Parses a tag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)/tags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_template_path(project: str,location: str,tag_template: str,) -> str: + """Returns a fully-qualified tag_template string.""" + return "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) + + @staticmethod + def parse_tag_template_path(path: str) -> Dict[str,str]: + """Parses a tag_template path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_template_field_path(project: str,location: str,tag_template: str,field: str,) -> str: + """Returns a fully-qualified tag_template_field string.""" + return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) + + @staticmethod + def parse_tag_template_field_path(path: str) -> Dict[str,str]: + """Parses a tag_template_field path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_template_field_enum_value_path(project: str,location: str,tag_template: str,tag_template_field_id: str,enum_value_display_name: str,) -> str: + """Returns a fully-qualified tag_template_field_enum_value string.""" + return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{tag_template_field_id}/enumValues/{enum_value_display_name}".format(project=project, location=location, tag_template=tag_template, tag_template_field_id=tag_template_field_id, enum_value_display_name=enum_value_display_name, ) + + @staticmethod + def parse_tag_template_field_enum_value_path(path: str) -> Dict[str,str]: + """Parses a tag_template_field_enum_value path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?P.+?)/enumValues/(?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, DataCatalogTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data catalog 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, DataCatalogTransport]): 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, DataCatalogTransport): + # transport is a DataCatalogTransport 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=True, + ) + + def search_catalog(self, + request: Union[datacatalog.SearchCatalogRequest, dict] = None, + *, + scope: datacatalog.SearchCatalogRequest.Scope = None, + query: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchCatalogPager: + r"""Searches Data Catalog for multiple resources like entries and + tags that match a query. + + This is a [Custom Method] + (https://cloud.google.com/apis/design/custom_methods) that + doesn't return all information on a resource, only its ID and + high level fields. To get more information, you can subsequently + call specific get methods. + + Note: Data Catalog search queries don't guarantee full recall. + Results that match your query might not be returned, even in + subsequent result pages. Additionally, returned (and not + returned) results can vary if you repeat search queries. + + For more information, see [Data Catalog search syntax] + (https://cloud.google.com/data-catalog/docs/how-to/search-reference). + + Args: + request (Union[google.cloud.datacatalog_v1.types.SearchCatalogRequest, dict]): + The request object. Request message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + scope (google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope): + Required. The scope of this search request. + + The ``scope`` is invalid if ``include_org_ids``, + ``include_project_ids`` are empty AND + ``include_gcp_public_datasets`` is set to ``false``. In + this case, the request returns an error. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Optional. The query string with a minimum of 3 + characters and specific syntax. For more information, + see `Data Catalog search + syntax `__. + + An empty query string returns all data assets (in the + specified scope) that you have access to. + + A query string can be a simple ``xyz`` or qualified by + predicates: + + - ``name:x`` + - ``column:y`` + - ``description:z`` + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.services.data_catalog.pagers.SearchCatalogPager: + Response message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + 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([scope, query]) + if request is 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 datacatalog.SearchCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.SearchCatalogRequest): + request = datacatalog.SearchCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_catalog] + + # 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.SearchCatalogPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entry_group(self, + request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, + *, + parent: str = None, + entry_group_id: str = None, + entry_group: datacatalog.EntryGroup = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Creates an entry group. + + An entry group contains logically related entries together with + `Cloud Identity and Access + Management `__ policies. These + policies specify users who can create, edit, and view entries + within entry groups. + + Data Catalog automatically creates entry groups with names that + start with the ``@`` symbol for the following resources: + + - BigQuery entries (``@bigquery``) + - Pub/Sub topics (``@pubsub``) + - Dataproc Metastore services + (``@dataproc_metastore_{SERVICE_NAME_HASH}``) + + You can create your own entry groups for Cloud Storage fileset + entries and custom entries together with the corresponding IAM + policies. User-created entry groups can't contain the ``@`` + symbol, it is reserved for automatically created groups. + + Entry groups, like entries, can be searched. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateEntryGroupRequest, dict]): + The request object. Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. + parent (str): + Required. The names of the project + and location that the new entry group + belongs to. Note: The entry group + itself and its child resources might not + be stored in the location specified in + its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group_id (str): + Required. The ID of the entry group to create. + + The ID must contain only letters (a-z, A-Z), numbers + (0-9), underscores (_), and must start with a letter or + underscore. The maximum size is 64 bytes when encoded in + UTF-8. + + This corresponds to the ``entry_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group (google.cloud.datacatalog_v1.types.EntryGroup): + The entry group to create. Defaults + to empty. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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, entry_group_id, entry_group]) + if request is 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 datacatalog.CreateEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateEntryGroupRequest): + request = datacatalog.CreateEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_group_id is not None: + request.entry_group_id = entry_group_id + if entry_group is not None: + request.entry_group = entry_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entry_group] + + # 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_entry_group(self, + request: Union[datacatalog.GetEntryGroupRequest, dict] = None, + *, + name: str = None, + read_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Gets an entry group. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetEntryGroupRequest, dict]): + The request object. Request message for + [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. + name (str): + Required. The name of the entry group + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return. If empty or + omitted, all fields are returned. + + This corresponds to the ``read_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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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, read_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 datacatalog.GetEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetEntryGroupRequest): + request = datacatalog.GetEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if read_mask is not None: + request.read_mask = read_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_entry_group] + + # Certain fields should be 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 update_entry_group(self, + request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, + *, + entry_group: datacatalog.EntryGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Updates an entry group. + + You must enable the Data Catalog API in the project identified + by the ``entry_group.name`` parameter. For more information, see + `Data Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateEntryGroupRequest, dict]): + The request object. Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. + entry_group (google.cloud.datacatalog_v1.types.EntryGroup): + Required. Updates for the entry group. The ``name`` + field must be set. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to + overwrite on an entry group. + If this parameter is absent or empty, + all modifiable fields are overwritten. + If such fields are non-required and + omitted in the request body, their + values are emptied. + + 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.datacatalog_v1.types.EntryGroup: + Entry group metadata. + + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1.Entry] resources. + + """ + # 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([entry_group, 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 datacatalog.UpdateEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateEntryGroupRequest): + request = datacatalog.UpdateEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry_group is not None: + request.entry_group = entry_group + 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_entry_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry_group.name", request.entry_group.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entry_group(self, + request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an entry group. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteEntryGroupRequest, dict]): + The request object. Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. + name (str): + Required. The name of the entry group + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 datacatalog.DeleteEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteEntryGroupRequest): + request = datacatalog.DeleteEntryGroupRequest(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_entry_group] + + # Certain fields should be 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_entry_groups(self, + request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntryGroupsPager: + r"""Lists entry groups. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListEntryGroupsRequest, dict]): + The request object. Request message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + parent (str): + Required. The name of the location + that contains the entry groups to list. + Can be provided as a URL. + + 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.datacatalog_v1.services.data_catalog.pagers.ListEntryGroupsPager: + Response message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + + 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 datacatalog.ListEntryGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListEntryGroupsRequest): + request = datacatalog.ListEntryGroupsRequest(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_entry_groups] + + # 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.ListEntryGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entry(self, + request: Union[datacatalog.CreateEntryRequest, dict] = None, + *, + parent: str = None, + entry_id: str = None, + entry: datacatalog.Entry = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Creates an entry. + + You can create entries only with 'FILESET', 'CLUSTER', + 'DATA_STREAM', or custom types. Data Catalog automatically + creates entries with other types during metadata ingestion from + integrated systems. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + An entry group can have a maximum of 100,000 entries. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateEntryRequest, dict]): + The request object. Request message for + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. + parent (str): + Required. The name of the entry group + this entry belongs to. + Note: The entry itself and its child + resources might not be stored in the + location specified in its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_id (str): + Required. The ID of the entry to create. + + The ID must contain only letters (a-z, A-Z), numbers + (0-9), and underscores (_). The maximum size is 64 bytes + when encoded in UTF-8. + + This corresponds to the ``entry_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry (google.cloud.datacatalog_v1.types.Entry): + Required. The entry to create. + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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, entry_id, entry]) + if request is 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 datacatalog.CreateEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateEntryRequest): + request = datacatalog.CreateEntryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_id is not None: + request.entry_id = entry_id + if entry is not None: + request.entry = entry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entry] + + # 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_entry(self, + request: Union[datacatalog.UpdateEntryRequest, dict] = None, + *, + entry: datacatalog.Entry = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Updates an existing entry. + + You must enable the Data Catalog API in the project identified + by the ``entry.name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateEntryRequest, dict]): + The request object. Request message for + [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. + entry (google.cloud.datacatalog_v1.types.Entry): + Required. Updates for the entry. The ``name`` field must + be set. + + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on an entry. + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied. + + You can modify only the fields listed below. + + For entries with type ``DATA_STREAM``: + + - ``schema`` + + For entries with type ``FILESET``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + For entries with ``user_specified_type``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``user_specified_type`` + - ``user_specified_system`` + - ``linked_resource`` + - ``source_system_timestamps`` + + 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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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([entry, 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 datacatalog.UpdateEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateEntryRequest): + request = datacatalog.UpdateEntryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry is not None: + request.entry = entry + 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_entry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry.name", request.entry.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entry(self, + request: Union[datacatalog.DeleteEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing entry. + + You can delete only the entries created by the + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] + method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteEntryRequest, dict]): + The request object. Request message for + [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. + name (str): + Required. The name of the entry to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 datacatalog.DeleteEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteEntryRequest): + request = datacatalog.DeleteEntryRequest(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_entry] + + # Certain fields should be 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_entry(self, + request: Union[datacatalog.GetEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetEntryRequest, dict]): + The request object. Request message for + [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. + name (str): + Required. The name of the entry to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # 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 datacatalog.GetEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetEntryRequest): + request = datacatalog.GetEntryRequest(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_entry] + + # Certain fields should be 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 lookup_entry(self, + request: Union[datacatalog.LookupEntryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry by its target resource name. + The resource name comes from the source Google Cloud + Platform service. + + Args: + request (Union[google.cloud.datacatalog_v1.types.LookupEntryRequest, dict]): + The request object. Request message for + [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Entry: + Entry metadata. + A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or + a Pub/Sub topic) or outside of it. You can use the + linked_resource field in the entry resource to refer + to the original resource ID of the source system. + + An entry resource contains resource details, for + example, its schema. Additionally, you can attach + flexible metadata to an entry in the form of a + [Tag][google.cloud.datacatalog.v1.Tag]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a datacatalog.LookupEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.LookupEntryRequest): + request = datacatalog.LookupEntryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lookup_entry] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_entries(self, + request: Union[datacatalog.ListEntriesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntriesPager: + r"""Lists entries. + + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): + The request object. Request message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + parent (str): + Required. The name of the entry group + that contains the entries to list. + Can be provided in URL format. + + 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.datacatalog_v1.services.data_catalog.pagers.ListEntriesPager: + Response message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + + 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 datacatalog.ListEntriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListEntriesRequest): + request = datacatalog.ListEntriesRequest(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_entries] + + # 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.ListEntriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tag_template(self, + request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, + *, + parent: str = None, + tag_template_id: str = None, + tag_template: tags.TagTemplate = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Creates a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateRequest, dict]): + The request object. Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. + parent (str): + Required. The name of the project and the template + location + `region `__. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_id (str): + Required. The ID of the tag template to create. + + The ID must contain only lowercase letters (a-z), + numbers (0-9), or underscores (_), and must start with a + letter or underscore. The maximum size is 64 bytes when + encoded in UTF-8. + + This corresponds to the ``tag_template_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template (google.cloud.datacatalog_v1.types.TagTemplate): + Required. The tag template to create. + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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, tag_template_id, tag_template]) + if request is 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 datacatalog.CreateTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagTemplateRequest): + request = datacatalog.CreateTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_id is not None: + request.tag_template_id = tag_template_id + if tag_template is not None: + request.tag_template = tag_template + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_template] + + # 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_tag_template(self, + request: Union[datacatalog.GetTagTemplateRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Gets a tag template. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetTagTemplateRequest, dict]): + The request object. Request message for + [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. + name (str): + Required. The name of the tag + template to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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 datacatalog.GetTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetTagTemplateRequest): + request = datacatalog.GetTagTemplateRequest(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_tag_template] + + # Certain fields should be 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 update_tag_template(self, + request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, + *, + tag_template: tags.TagTemplate = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Updates a tag template. + + You can't update template fields with this method. These fields + are separate resources with their own create, update, and delete + methods. + + You must enable the Data Catalog API in the project identified + by the ``tag_template.name`` parameter. For more information, + see `Data Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateRequest, dict]): + The request object. Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. + tag_template (google.cloud.datacatalog_v1.types.TagTemplate): + Required. The template to update. The ``name`` field + must be set. + + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on a tag + template. Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied. + + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. + + 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.datacatalog_v1.types.TagTemplate: + A tag template defines a tag that can have one or more + typed fields. + + The template is used to create tags that are attached + to GCP resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. For example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag + template to tag resources. + + """ + # 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([tag_template, 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 datacatalog.UpdateTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagTemplateRequest): + request = datacatalog.UpdateTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_template is not None: + request.tag_template = tag_template + 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_tag_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_template.name", request.tag_template.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tag_template(self, + request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag template and all tags that use it. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateRequest, dict]): + The request object. Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. + name (str): + Required. The name of the tag + template to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Required. If true, deletes all tags that use this + template. + + Currently, ``true`` is the only supported value. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 datacatalog.DeleteTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagTemplateRequest): + request = datacatalog.DeleteTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_template] + + # Certain fields should be 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 create_tag_template_field(self, + request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, + *, + parent: str = None, + tag_template_field_id: str = None, + tag_template_field: tags.TagTemplateField = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Creates a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateFieldRequest, dict]): + The request object. Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. + parent (str): + Required. The name of the project and the template + location + `region `__. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field_id (str): + Required. The ID of the tag template field to create. + + Note: Adding a required field to an existing template is + *not* allowed. + + Field IDs can contain letters (both uppercase and + lowercase), numbers (0-9), underscores (_) and dashes + (-). Field IDs must be at least 1 character long and at + most 128 characters long. Field IDs must also be unique + within their template. + + This corresponds to the ``tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): + Required. The tag template field to + create. + + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field_id, tag_template_field]) + if request is 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 datacatalog.CreateTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagTemplateFieldRequest): + request = datacatalog.CreateTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_field_id is not None: + request.tag_template_field_id = tag_template_field_id + if tag_template_field is not None: + request.tag_template_field = tag_template_field + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_template_field] + + # 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_tag_template_field(self, + request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + tag_template_field: tags.TagTemplateField = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Updates a field in a tag template. + + You can't update the field type with this method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateFieldRequest, dict]): + The request object. Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. + name (str): + Required. The name of the tag + template field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): + Required. The template to update. + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Names of fields whose values to overwrite on + an individual field of a tag template. The following + fields are modifiable: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If this parameter is absent or empty, all modifiable + fields are overwritten. If such fields are non-required + and omitted in the request body, their values are + emptied with one exception: when updating an enum type, + the provided values are merged with the existing values. + Therefore, enum values can only be added, existing enum + values cannot be deleted or renamed. + + Additionally, updating a template field from optional to + required is *not* allowed. + + 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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field, 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 datacatalog.UpdateTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagTemplateFieldRequest): + request = datacatalog.UpdateTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if tag_template_field is not None: + request.tag_template_field = tag_template_field + 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_tag_template_field] + + # Certain fields should be 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 rename_tag_template_field(self, + request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + new_tag_template_field_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Args: + request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldRequest, dict]): + The request object. Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. + name (str): + Required. The name of the tag + template field. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_tag_template_field_id (str): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + + This corresponds to the ``new_tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_tag_template_field_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datacatalog.RenameTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.RenameTagTemplateFieldRequest): + request = datacatalog.RenameTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_tag_template_field_id is not None: + request.new_tag_template_field_id = new_tag_template_field_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field] + + # Certain fields should be 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 rename_tag_template_field_enum_value(self, + request: Union[datacatalog.RenameTagTemplateFieldEnumValueRequest, dict] = None, + *, + name: str = None, + new_enum_value_display_name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames an enum value in a tag template. + Within a single enum field, enum values must be unique. + + Args: + request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldEnumValueRequest, dict]): + The request object. Request message for + [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. + name (str): + Required. The name of the enum field + value. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_enum_value_display_name (str): + Required. The new display name of the enum value. For + example, ``my_new_enum_value``. + + This corresponds to the ``new_enum_value_display_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.datacatalog_v1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_enum_value_display_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 datacatalog.RenameTagTemplateFieldEnumValueRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.RenameTagTemplateFieldEnumValueRequest): + request = datacatalog.RenameTagTemplateFieldEnumValueRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_enum_value_display_name is not None: + request.new_enum_value_display_name = new_enum_value_display_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field_enum_value] + + # Certain fields should be 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_tag_template_field(self, + request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a field in a tag template and all uses of this field + from the tags based on this template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateFieldRequest, dict]): + The request object. Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. + name (str): + Required. The name of the tag + template field to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Required. If true, deletes this field from any tags that + use it. + + Currently, ``true`` is the only supported value. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 datacatalog.DeleteTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagTemplateFieldRequest): + request = datacatalog.DeleteTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_template_field] + + # Certain fields should be 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 create_tag(self, + request: Union[datacatalog.CreateTagRequest, dict] = None, + *, + parent: str = None, + tag: tags.Tag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Creates a tag and assigns it to: + + - An [Entry][google.cloud.datacatalog.v1.Entry] if the method + name is + ``projects.locations.entryGroups.entries.tags.create``. + - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the + method name is + ``projects.locations.entryGroups.tags.create``. + + Note: The project identified by the ``parent`` parameter for the + [tag] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) + and the [tag template] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) + used to create the tag must be in the same organization. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTagRequest, dict]): + The request object. Request message for + [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. + parent (str): + Required. The name of the resource to + attach this tag to. + Tags can be attached to entries or entry + groups. An entry can have up to 1000 + attached tags. + + Note: The tag and its child resources + might not be stored in the location + specified in its name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag (google.cloud.datacatalog_v1.types.Tag): + Required. The tag to create. + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Tag: + Tags contain custom metadata and are attached to Data Catalog resources. Tags + conform with the specification of their tag template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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, tag]) + if request is 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 datacatalog.CreateTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagRequest): + request = datacatalog.CreateTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag is not None: + request.tag = tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag] + + # 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_tag(self, + request: Union[datacatalog.UpdateTagRequest, dict] = None, + *, + tag: tags.Tag = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Updates an existing tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTagRequest, dict]): + The request object. Request message for + [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. + tag (google.cloud.datacatalog_v1.types.Tag): + Required. The updated tag. The "name" + field must be set. + + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on a tag. + Currently, a tag has the only modifiable field with the + name ``fields``. + + In general, if this parameter is absent or empty, all + modifiable fields are overwritten. If such fields are + non-required and omitted in the request body, their + values are emptied. + + 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.datacatalog_v1.types.Tag: + Tags contain custom metadata and are attached to Data Catalog resources. Tags + conform with the specification of their tag template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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([tag, 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 datacatalog.UpdateTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagRequest): + request = datacatalog.UpdateTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag is not None: + request.tag = tag + 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_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag.name", request.tag.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tag(self, + request: Union[datacatalog.DeleteTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTagRequest, dict]): + The request object. Request message for + [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. + name (str): + Required. The name of the tag to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 datacatalog.DeleteTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagRequest): + request = datacatalog.DeleteTagRequest(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_tag] + + # Certain fields should be 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_tags(self, + request: Union[datacatalog.ListTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTagsPager: + r"""Lists tags assigned to an + [Entry][google.cloud.datacatalog.v1.Entry]. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListTagsRequest, dict]): + The request object. Request message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + parent (str): + Required. The name of the Data Catalog resource to list + the tags of. + + The resource can be an + [Entry][google.cloud.datacatalog.v1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] + (without ``/entries/{entries}`` at the end). + + 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.datacatalog_v1.services.data_catalog.pagers.ListTagsPager: + Response message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + + 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 datacatalog.ListTagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListTagsRequest): + request = datacatalog.ListTagsRequest(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_tags] + + # 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.ListTagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets an access control policy for a resource. Replaces any + existing policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method sets policies only within Data Catalog and + can't be used to manage policies in BigQuery, Pub/Sub, Dataproc + Metastore, and any external Google Cloud Platform resources + synced with the Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. + + May return: + + - A\ ``NOT_FOUND`` error if the resource doesn't exist or you + don't have the permission to view it. + - An empty policy if the resource exists but doesn't have a set + policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method doesn't get policies from Google Cloud + Platform resources ingested into Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Gets your permissions on a resource. + Returns an empty set of permissions if the resource + doesn't exist. + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method gets policies only within Data Catalog + and can't be used to get policies from BigQuery, + Pub/Sub, Dataproc Metastore, and any external Google + Cloud Platform resources ingested into Data Catalog. + No Google IAM permissions are required to call this + method. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataCatalogClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py new file mode 100644 index 00000000..20096de6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py @@ -0,0 +1,508 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import search +from google.cloud.datacatalog_v1.types import tags + + +class SearchCatalogPager: + """A pager for iterating through ``search_catalog`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchCatalog`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` + 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[..., datacatalog.SearchCatalogResponse], + request: datacatalog.SearchCatalogRequest, + response: datacatalog.SearchCatalogResponse, + *, + 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.datacatalog_v1.types.SearchCatalogRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.SearchCatalogResponse): + 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 = datacatalog.SearchCatalogRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.SearchCatalogResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search.SearchCatalogResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchCatalogAsyncPager: + """A pager for iterating through ``search_catalog`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchCatalog`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` + 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[datacatalog.SearchCatalogResponse]], + request: datacatalog.SearchCatalogRequest, + response: datacatalog.SearchCatalogResponse, + *, + 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.datacatalog_v1.types.SearchCatalogRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.SearchCatalogResponse): + 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 = datacatalog.SearchCatalogRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.SearchCatalogResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[search.SearchCatalogResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntryGroupsPager: + """A pager for iterating through ``list_entry_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entry_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntryGroups`` requests and continue to iterate + through the ``entry_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` + 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[..., datacatalog.ListEntryGroupsResponse], + request: datacatalog.ListEntryGroupsRequest, + response: datacatalog.ListEntryGroupsResponse, + *, + 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.datacatalog_v1.types.ListEntryGroupsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListEntryGroupsResponse): + 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 = datacatalog.ListEntryGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListEntryGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[datacatalog.EntryGroup]: + for page in self.pages: + yield from page.entry_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntryGroupsAsyncPager: + """A pager for iterating through ``list_entry_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entry_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntryGroups`` requests and continue to iterate + through the ``entry_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` + 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[datacatalog.ListEntryGroupsResponse]], + request: datacatalog.ListEntryGroupsRequest, + response: datacatalog.ListEntryGroupsResponse, + *, + 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.datacatalog_v1.types.ListEntryGroupsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListEntryGroupsResponse): + 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 = datacatalog.ListEntryGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListEntryGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[datacatalog.EntryGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.entry_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntriesPager: + """A pager for iterating through ``list_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` + 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[..., datacatalog.ListEntriesResponse], + request: datacatalog.ListEntriesRequest, + response: datacatalog.ListEntriesResponse, + *, + 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.datacatalog_v1.types.ListEntriesRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListEntriesResponse): + 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 = datacatalog.ListEntriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[datacatalog.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntriesAsyncPager: + """A pager for iterating through ``list_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` + 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[datacatalog.ListEntriesResponse]], + request: datacatalog.ListEntriesRequest, + response: datacatalog.ListEntriesResponse, + *, + 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.datacatalog_v1.types.ListEntriesRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListEntriesResponse): + 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 = datacatalog.ListEntriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[datacatalog.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagsPager: + """A pager for iterating through ``list_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTags`` requests and continue to iterate + through the ``tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` + 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[..., datacatalog.ListTagsResponse], + request: datacatalog.ListTagsRequest, + response: datacatalog.ListTagsResponse, + *, + 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.datacatalog_v1.types.ListTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListTagsResponse): + 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 = datacatalog.ListTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tags.Tag]: + for page in self.pages: + yield from page.tags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagsAsyncPager: + """A pager for iterating through ``list_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTags`` requests and continue to iterate + through the ``tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` + 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[datacatalog.ListTagsResponse]], + request: datacatalog.ListTagsRequest, + response: datacatalog.ListTagsResponse, + *, + 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.datacatalog_v1.types.ListTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListTagsResponse): + 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 = datacatalog.ListTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[tags.Tag]: + async def async_generator(): + async for page in self.pages: + for response in page.tags: + 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/datacatalog_v1/services/data_catalog/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/__init__.py new file mode 100644 index 00000000..f8baae0c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/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 DataCatalogTransport +from .grpc import DataCatalogGrpcTransport +from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]] +_transport_registry['grpc'] = DataCatalogGrpcTransport +_transport_registry['grpc_asyncio'] = DataCatalogGrpcAsyncIOTransport + +__all__ = ( + 'DataCatalogTransport', + 'DataCatalogGrpcTransport', + 'DataCatalogGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py new file mode 100644 index 00000000..a6522705 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py @@ -0,0 +1,576 @@ +# -*- 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 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.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class DataCatalogTransport(abc.ABC): + """Abstract transport class for DataCatalog.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search_catalog: gapic_v1.method.wrap_method( + self.search_catalog, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_entry_group: gapic_v1.method.wrap_method( + self.create_entry_group, + default_timeout=None, + client_info=client_info, + ), + self.get_entry_group: gapic_v1.method.wrap_method( + self.get_entry_group, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_entry_group: gapic_v1.method.wrap_method( + self.update_entry_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_entry_group: gapic_v1.method.wrap_method( + self.delete_entry_group, + default_timeout=None, + client_info=client_info, + ), + self.list_entry_groups: gapic_v1.method.wrap_method( + self.list_entry_groups, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_entry: gapic_v1.method.wrap_method( + self.create_entry, + default_timeout=None, + client_info=client_info, + ), + self.update_entry: gapic_v1.method.wrap_method( + self.update_entry, + default_timeout=None, + client_info=client_info, + ), + self.delete_entry: gapic_v1.method.wrap_method( + self.delete_entry, + default_timeout=None, + client_info=client_info, + ), + self.get_entry: gapic_v1.method.wrap_method( + self.get_entry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.lookup_entry: gapic_v1.method.wrap_method( + self.lookup_entry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_entries: gapic_v1.method.wrap_method( + self.list_entries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag_template: gapic_v1.method.wrap_method( + self.create_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.get_tag_template: gapic_v1.method.wrap_method( + self.get_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.update_tag_template: gapic_v1.method.wrap_method( + self.update_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag_template: gapic_v1.method.wrap_method( + self.delete_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.create_tag_template_field: gapic_v1.method.wrap_method( + self.create_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.update_tag_template_field: gapic_v1.method.wrap_method( + self.update_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.rename_tag_template_field: gapic_v1.method.wrap_method( + self.rename_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.rename_tag_template_field_enum_value: gapic_v1.method.wrap_method( + self.rename_tag_template_field_enum_value, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag_template_field: gapic_v1.method.wrap_method( + self.delete_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.create_tag: gapic_v1.method.wrap_method( + self.create_tag, + default_timeout=None, + client_info=client_info, + ), + self.update_tag: gapic_v1.method.wrap_method( + self.update_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag: gapic_v1.method.wrap_method( + self.delete_tag, + default_timeout=None, + client_info=client_info, + ), + self.list_tags: gapic_v1.method.wrap_method( + self.list_tags, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + Union[ + datacatalog.SearchCatalogResponse, + Awaitable[datacatalog.SearchCatalogResponse] + ]]: + raise NotImplementedError() + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + Union[ + datacatalog.ListEntryGroupsResponse, + Awaitable[datacatalog.ListEntryGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + Union[ + datacatalog.ListEntriesResponse, + Awaitable[datacatalog.ListEntriesResponse] + ]]: + raise NotImplementedError() + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def rename_tag_template_field_enum_value(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldEnumValueRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + Union[ + tags.Tag, + Awaitable[tags.Tag] + ]]: + raise NotImplementedError() + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + Union[ + tags.Tag, + Awaitable[tags.Tag] + ]]: + raise NotImplementedError() + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + Union[ + datacatalog.ListTagsResponse, + Awaitable[datacatalog.ListTagsResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DataCatalogTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py new file mode 100644 index 00000000..4132c37e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py @@ -0,0 +1,1161 @@ +# -*- 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.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO + + +class DataCatalogGrpcTransport(DataCatalogTransport): + """gRPC backend transport for DataCatalog. + + Data Catalog API service allows you to discover, understand, + and manage your data. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + datacatalog.SearchCatalogResponse]: + r"""Return a callable for the search catalog method over gRPC. + + Searches Data Catalog for multiple resources like entries and + tags that match a query. + + This is a [Custom Method] + (https://cloud.google.com/apis/design/custom_methods) that + doesn't return all information on a resource, only its ID and + high level fields. To get more information, you can subsequently + call specific get methods. + + Note: Data Catalog search queries don't guarantee full recall. + Results that match your query might not be returned, even in + subsequent result pages. Additionally, returned (and not + returned) results can vary if you repeat search queries. + + For more information, see [Data Catalog search syntax] + (https://cloud.google.com/data-catalog/docs/how-to/search-reference). + + Returns: + Callable[[~.SearchCatalogRequest], + ~.SearchCatalogResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_catalog' not in self._stubs: + self._stubs['search_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/SearchCatalog', + request_serializer=datacatalog.SearchCatalogRequest.serialize, + response_deserializer=datacatalog.SearchCatalogResponse.deserialize, + ) + return self._stubs['search_catalog'] + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the create entry group method over gRPC. + + Creates an entry group. + + An entry group contains logically related entries together with + `Cloud Identity and Access + Management `__ policies. These + policies specify users who can create, edit, and view entries + within entry groups. + + Data Catalog automatically creates entry groups with names that + start with the ``@`` symbol for the following resources: + + - BigQuery entries (``@bigquery``) + - Pub/Sub topics (``@pubsub``) + - Dataproc Metastore services + (``@dataproc_metastore_{SERVICE_NAME_HASH}``) + + You can create your own entry groups for Cloud Storage fileset + entries and custom entries together with the corresponding IAM + policies. User-created entry groups can't contain the ``@`` + symbol, it is reserved for automatically created groups. + + Entry groups, like entries, can be searched. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.CreateEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateEntryGroup', + request_serializer=datacatalog.CreateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['create_entry_group'] + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the get entry group method over gRPC. + + Gets an entry group. + + Returns: + Callable[[~.GetEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetEntryGroup', + request_serializer=datacatalog.GetEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['get_entry_group'] + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the update entry group method over gRPC. + + Updates an entry group. + + You must enable the Data Catalog API in the project identified + by the ``entry_group.name`` parameter. For more information, see + `Data Catalog resource + project `__. + + Returns: + Callable[[~.UpdateEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntryGroup', + request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['update_entry_group'] + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entry group method over gRPC. + + Deletes an entry group. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteEntryGroupRequest], + ~.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_entry_group' not in self._stubs: + self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntryGroup', + request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry_group'] + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + datacatalog.ListEntryGroupsResponse]: + r"""Return a callable for the list entry groups method over gRPC. + + Lists entry groups. + + Returns: + Callable[[~.ListEntryGroupsRequest], + ~.ListEntryGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: + self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListEntryGroups', + request_serializer=datacatalog.ListEntryGroupsRequest.serialize, + response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, + ) + return self._stubs['list_entry_groups'] + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the create entry method over gRPC. + + Creates an entry. + + You can create entries only with 'FILESET', 'CLUSTER', + 'DATA_STREAM', or custom types. Data Catalog automatically + creates entries with other types during metadata ingestion from + integrated systems. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + An entry group can have a maximum of 100,000 entries. + + Returns: + Callable[[~.CreateEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['create_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateEntry', + request_serializer=datacatalog.CreateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['create_entry'] + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the update entry method over gRPC. + + Updates an existing entry. + + You must enable the Data Catalog API in the project identified + by the ``entry.name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.UpdateEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['update_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntry', + request_serializer=datacatalog.UpdateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['update_entry'] + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entry method over gRPC. + + Deletes an existing entry. + + You can delete only the entries created by the + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] + method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteEntryRequest], + ~.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_entry' not in self._stubs: + self._stubs['delete_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntry', + request_serializer=datacatalog.DeleteEntryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry'] + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the get entry method over gRPC. + + Gets an entry. + + Returns: + Callable[[~.GetEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['get_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetEntry', + request_serializer=datacatalog.GetEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['get_entry'] + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the lookup entry method over gRPC. + + Gets an entry by its target resource name. + The resource name comes from the source Google Cloud + Platform service. + + Returns: + Callable[[~.LookupEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_entry' not in self._stubs: + self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/LookupEntry', + request_serializer=datacatalog.LookupEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['lookup_entry'] + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + datacatalog.ListEntriesResponse]: + r"""Return a callable for the list entries method over gRPC. + + Lists entries. + + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Returns: + Callable[[~.ListEntriesRequest], + ~.ListEntriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entries' not in self._stubs: + self._stubs['list_entries'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListEntries', + request_serializer=datacatalog.ListEntriesRequest.serialize, + response_deserializer=datacatalog.ListEntriesResponse.deserialize, + ) + return self._stubs['list_entries'] + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the create tag template method over gRPC. + + Creates a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Returns: + Callable[[~.CreateTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplate', + request_serializer=datacatalog.CreateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['create_tag_template'] + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the get tag template method over gRPC. + + Gets a tag template. + + Returns: + Callable[[~.GetTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetTagTemplate', + request_serializer=datacatalog.GetTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['get_tag_template'] + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the update tag template method over gRPC. + + Updates a tag template. + + You can't update template fields with this method. These fields + are separate resources with their own create, update, and delete + methods. + + You must enable the Data Catalog API in the project identified + by the ``tag_template.name`` parameter. For more information, + see `Data Catalog resource + project `__. + + Returns: + Callable[[~.UpdateTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplate', + request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['update_tag_template'] + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag template method over gRPC. + + Deletes a tag template and all tags that use it. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteTagTemplateRequest], + ~.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_tag_template' not in self._stubs: + self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplate', + request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template'] + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the create tag template field method over gRPC. + + Creates a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.CreateTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplateField', + request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['create_tag_template_field'] + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the update tag template field method over gRPC. + + Updates a field in a tag template. + + You can't update the field type with this method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.UpdateTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplateField', + request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['update_tag_template_field'] + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the rename tag template field method over gRPC. + + Renames a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Returns: + Callable[[~.RenameTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field' not in self._stubs: + self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateField', + request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field'] + + @property + def rename_tag_template_field_enum_value(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldEnumValueRequest], + tags.TagTemplateField]: + r"""Return a callable for the rename tag template field enum + value method over gRPC. + + Renames an enum value in a tag template. + Within a single enum field, enum values must be unique. + + Returns: + Callable[[~.RenameTagTemplateFieldEnumValueRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field_enum_value' not in self._stubs: + self._stubs['rename_tag_template_field_enum_value'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateFieldEnumValue', + request_serializer=datacatalog.RenameTagTemplateFieldEnumValueRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field_enum_value'] + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag template field method over gRPC. + + Deletes a field in a tag template and all uses of this field + from the tags based on this template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteTagTemplateFieldRequest], + ~.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_tag_template_field' not in self._stubs: + self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplateField', + request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template_field'] + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + tags.Tag]: + r"""Return a callable for the create tag method over gRPC. + + Creates a tag and assigns it to: + + - An [Entry][google.cloud.datacatalog.v1.Entry] if the method + name is + ``projects.locations.entryGroups.entries.tags.create``. + - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the + method name is + ``projects.locations.entryGroups.tags.create``. + + Note: The project identified by the ``parent`` parameter for the + [tag] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) + and the [tag template] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) + used to create the tag must be in the same organization. + + Returns: + Callable[[~.CreateTagRequest], + ~.Tag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['create_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTag', + request_serializer=datacatalog.CreateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['create_tag'] + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + tags.Tag]: + r"""Return a callable for the update tag method over gRPC. + + Updates an existing tag. + + Returns: + Callable[[~.UpdateTagRequest], + ~.Tag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['update_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTag', + request_serializer=datacatalog.UpdateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['update_tag'] + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag method over gRPC. + + Deletes a tag. + + Returns: + Callable[[~.DeleteTagRequest], + ~.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_tag' not in self._stubs: + self._stubs['delete_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTag', + request_serializer=datacatalog.DeleteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag'] + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + datacatalog.ListTagsResponse]: + r"""Return a callable for the list tags method over gRPC. + + Lists tags assigned to an + [Entry][google.cloud.datacatalog.v1.Entry]. + + Returns: + Callable[[~.ListTagsRequest], + ~.ListTagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tags' not in self._stubs: + self._stubs['list_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListTags', + request_serializer=datacatalog.ListTagsRequest.serialize, + response_deserializer=datacatalog.ListTagsResponse.deserialize, + ) + return self._stubs['list_tags'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets an access control policy for a resource. Replaces any + existing policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method sets policies only within Data Catalog and + can't be used to manage policies in BigQuery, Pub/Sub, Dataproc + Metastore, and any external Google Cloud Platform resources + synced with the Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + + May return: + + - A\ ``NOT_FOUND`` error if the resource doesn't exist or you + don't have the permission to view it. + - An empty policy if the resource exists but doesn't have a set + policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method doesn't get policies from Google Cloud + Platform resources ingested into Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Gets your permissions on a resource. + Returns an empty set of permissions if the resource + doesn't exist. + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method gets policies only within Data Catalog + and can't be used to get policies from BigQuery, + Pub/Sub, Dataproc Metastore, and any external Google + Cloud Platform resources ingested into Data Catalog. + No Google IAM permissions are required to call this + method. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DataCatalogGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py new file mode 100644 index 00000000..e68d47aa --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py @@ -0,0 +1,1165 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .grpc import DataCatalogGrpcTransport + + +class DataCatalogGrpcAsyncIOTransport(DataCatalogTransport): + """gRPC AsyncIO backend transport for DataCatalog. + + Data Catalog API service allows you to discover, understand, + and manage your data. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + Awaitable[datacatalog.SearchCatalogResponse]]: + r"""Return a callable for the search catalog method over gRPC. + + Searches Data Catalog for multiple resources like entries and + tags that match a query. + + This is a [Custom Method] + (https://cloud.google.com/apis/design/custom_methods) that + doesn't return all information on a resource, only its ID and + high level fields. To get more information, you can subsequently + call specific get methods. + + Note: Data Catalog search queries don't guarantee full recall. + Results that match your query might not be returned, even in + subsequent result pages. Additionally, returned (and not + returned) results can vary if you repeat search queries. + + For more information, see [Data Catalog search syntax] + (https://cloud.google.com/data-catalog/docs/how-to/search-reference). + + Returns: + Callable[[~.SearchCatalogRequest], + Awaitable[~.SearchCatalogResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_catalog' not in self._stubs: + self._stubs['search_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/SearchCatalog', + request_serializer=datacatalog.SearchCatalogRequest.serialize, + response_deserializer=datacatalog.SearchCatalogResponse.deserialize, + ) + return self._stubs['search_catalog'] + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the create entry group method over gRPC. + + Creates an entry group. + + An entry group contains logically related entries together with + `Cloud Identity and Access + Management `__ policies. These + policies specify users who can create, edit, and view entries + within entry groups. + + Data Catalog automatically creates entry groups with names that + start with the ``@`` symbol for the following resources: + + - BigQuery entries (``@bigquery``) + - Pub/Sub topics (``@pubsub``) + - Dataproc Metastore services + (``@dataproc_metastore_{SERVICE_NAME_HASH}``) + + You can create your own entry groups for Cloud Storage fileset + entries and custom entries together with the corresponding IAM + policies. User-created entry groups can't contain the ``@`` + symbol, it is reserved for automatically created groups. + + Entry groups, like entries, can be searched. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.CreateEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateEntryGroup', + request_serializer=datacatalog.CreateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['create_entry_group'] + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the get entry group method over gRPC. + + Gets an entry group. + + Returns: + Callable[[~.GetEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetEntryGroup', + request_serializer=datacatalog.GetEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['get_entry_group'] + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the update entry group method over gRPC. + + Updates an entry group. + + You must enable the Data Catalog API in the project identified + by the ``entry_group.name`` parameter. For more information, see + `Data Catalog resource + project `__. + + Returns: + Callable[[~.UpdateEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntryGroup', + request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['update_entry_group'] + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entry group method over gRPC. + + Deletes an entry group. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteEntryGroupRequest], + 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_entry_group' not in self._stubs: + self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntryGroup', + request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry_group'] + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + Awaitable[datacatalog.ListEntryGroupsResponse]]: + r"""Return a callable for the list entry groups method over gRPC. + + Lists entry groups. + + Returns: + Callable[[~.ListEntryGroupsRequest], + Awaitable[~.ListEntryGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: + self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListEntryGroups', + request_serializer=datacatalog.ListEntryGroupsRequest.serialize, + response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, + ) + return self._stubs['list_entry_groups'] + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the create entry method over gRPC. + + Creates an entry. + + You can create entries only with 'FILESET', 'CLUSTER', + 'DATA_STREAM', or custom types. Data Catalog automatically + creates entries with other types during metadata ingestion from + integrated systems. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + An entry group can have a maximum of 100,000 entries. + + Returns: + Callable[[~.CreateEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['create_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateEntry', + request_serializer=datacatalog.CreateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['create_entry'] + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the update entry method over gRPC. + + Updates an existing entry. + + You must enable the Data Catalog API in the project identified + by the ``entry.name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.UpdateEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['update_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntry', + request_serializer=datacatalog.UpdateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['update_entry'] + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entry method over gRPC. + + Deletes an existing entry. + + You can delete only the entries created by the + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] + method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteEntryRequest], + 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_entry' not in self._stubs: + self._stubs['delete_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntry', + request_serializer=datacatalog.DeleteEntryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry'] + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the get entry method over gRPC. + + Gets an entry. + + Returns: + Callable[[~.GetEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['get_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetEntry', + request_serializer=datacatalog.GetEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['get_entry'] + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the lookup entry method over gRPC. + + Gets an entry by its target resource name. + The resource name comes from the source Google Cloud + Platform service. + + Returns: + Callable[[~.LookupEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_entry' not in self._stubs: + self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/LookupEntry', + request_serializer=datacatalog.LookupEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['lookup_entry'] + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + Awaitable[datacatalog.ListEntriesResponse]]: + r"""Return a callable for the list entries method over gRPC. + + Lists entries. + + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Returns: + Callable[[~.ListEntriesRequest], + Awaitable[~.ListEntriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entries' not in self._stubs: + self._stubs['list_entries'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListEntries', + request_serializer=datacatalog.ListEntriesRequest.serialize, + response_deserializer=datacatalog.ListEntriesResponse.deserialize, + ) + return self._stubs['list_entries'] + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the create tag template method over gRPC. + + Creates a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Returns: + Callable[[~.CreateTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplate', + request_serializer=datacatalog.CreateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['create_tag_template'] + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the get tag template method over gRPC. + + Gets a tag template. + + Returns: + Callable[[~.GetTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetTagTemplate', + request_serializer=datacatalog.GetTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['get_tag_template'] + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the update tag template method over gRPC. + + Updates a tag template. + + You can't update template fields with this method. These fields + are separate resources with their own create, update, and delete + methods. + + You must enable the Data Catalog API in the project identified + by the ``tag_template.name`` parameter. For more information, + see `Data Catalog resource + project `__. + + Returns: + Callable[[~.UpdateTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplate', + request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['update_tag_template'] + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag template method over gRPC. + + Deletes a tag template and all tags that use it. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteTagTemplateRequest], + 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_tag_template' not in self._stubs: + self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplate', + request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template'] + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the create tag template field method over gRPC. + + Creates a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``parent`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.CreateTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplateField', + request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['create_tag_template_field'] + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the update tag template field method over gRPC. + + Updates a field in a tag template. + + You can't update the field type with this method. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.UpdateTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplateField', + request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['update_tag_template_field'] + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the rename tag template field method over gRPC. + + Renames a field in a tag template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see [Data + Catalog resource project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project). + + Returns: + Callable[[~.RenameTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field' not in self._stubs: + self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateField', + request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field'] + + @property + def rename_tag_template_field_enum_value(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldEnumValueRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the rename tag template field enum + value method over gRPC. + + Renames an enum value in a tag template. + Within a single enum field, enum values must be unique. + + Returns: + Callable[[~.RenameTagTemplateFieldEnumValueRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field_enum_value' not in self._stubs: + self._stubs['rename_tag_template_field_enum_value'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateFieldEnumValue', + request_serializer=datacatalog.RenameTagTemplateFieldEnumValueRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field_enum_value'] + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag template field method over gRPC. + + Deletes a field in a tag template and all uses of this field + from the tags based on this template. + + You must enable the Data Catalog API in the project identified + by the ``name`` parameter. For more information, see `Data + Catalog resource + project `__. + + Returns: + Callable[[~.DeleteTagTemplateFieldRequest], + 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_tag_template_field' not in self._stubs: + self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplateField', + request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template_field'] + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + Awaitable[tags.Tag]]: + r"""Return a callable for the create tag method over gRPC. + + Creates a tag and assigns it to: + + - An [Entry][google.cloud.datacatalog.v1.Entry] if the method + name is + ``projects.locations.entryGroups.entries.tags.create``. + - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the + method name is + ``projects.locations.entryGroups.tags.create``. + + Note: The project identified by the ``parent`` parameter for the + [tag] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) + and the [tag template] + (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) + used to create the tag must be in the same organization. + + Returns: + Callable[[~.CreateTagRequest], + Awaitable[~.Tag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['create_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/CreateTag', + request_serializer=datacatalog.CreateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['create_tag'] + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + Awaitable[tags.Tag]]: + r"""Return a callable for the update tag method over gRPC. + + Updates an existing tag. + + Returns: + Callable[[~.UpdateTagRequest], + Awaitable[~.Tag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['update_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/UpdateTag', + request_serializer=datacatalog.UpdateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['update_tag'] + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag method over gRPC. + + Deletes a tag. + + Returns: + Callable[[~.DeleteTagRequest], + 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_tag' not in self._stubs: + self._stubs['delete_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/DeleteTag', + request_serializer=datacatalog.DeleteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag'] + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + Awaitable[datacatalog.ListTagsResponse]]: + r"""Return a callable for the list tags method over gRPC. + + Lists tags assigned to an + [Entry][google.cloud.datacatalog.v1.Entry]. + + Returns: + Callable[[~.ListTagsRequest], + Awaitable[~.ListTagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tags' not in self._stubs: + self._stubs['list_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/ListTags', + request_serializer=datacatalog.ListTagsRequest.serialize, + response_deserializer=datacatalog.ListTagsResponse.deserialize, + ) + return self._stubs['list_tags'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets an access control policy for a resource. Replaces any + existing policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method sets policies only within Data Catalog and + can't be used to manage policies in BigQuery, Pub/Sub, Dataproc + Metastore, and any external Google Cloud Platform resources + synced with the Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + + May return: + + - A\ ``NOT_FOUND`` error if the resource doesn't exist or you + don't have the permission to view it. + - An empty policy if the resource exists but doesn't have a set + policy. + + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method doesn't get policies from Google Cloud + Platform resources ingested into Data Catalog. + + To call this method, you must have the following Google IAM + permissions: + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Gets your permissions on a resource. + Returns an empty set of permissions if the resource + doesn't exist. + Supported resources are: + + - Tag templates + - Entry groups + + Note: This method gets policies only within Data Catalog + and can't be used to get policies from BigQuery, + Pub/Sub, Dataproc Metastore, and any external Google + Cloud Platform resources ingested into Data Catalog. + No Google IAM permissions are required to call this + method. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.DataCatalog/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DataCatalogGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py new file mode 100644 index 00000000..3d4e08a0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__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 PolicyTagManagerClient +from .async_client import PolicyTagManagerAsyncClient + +__all__ = ( + 'PolicyTagManagerClient', + 'PolicyTagManagerAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py new file mode 100644 index 00000000..a0448861 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py @@ -0,0 +1,1300 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport +from .client import PolicyTagManagerClient + + +class PolicyTagManagerAsyncClient: + """Policy Tag Manager API service allows you to manage your + policy tags and taxonomies. + + Policy tags are used to tag BigQuery columns and apply + additional access control policies. A taxonomy is a hierarchical + grouping of policy tags that classify data along a common axis. + """ + + _client: PolicyTagManagerClient + + DEFAULT_ENDPOINT = PolicyTagManagerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyTagManagerClient.DEFAULT_MTLS_ENDPOINT + + policy_tag_path = staticmethod(PolicyTagManagerClient.policy_tag_path) + parse_policy_tag_path = staticmethod(PolicyTagManagerClient.parse_policy_tag_path) + taxonomy_path = staticmethod(PolicyTagManagerClient.taxonomy_path) + parse_taxonomy_path = staticmethod(PolicyTagManagerClient.parse_taxonomy_path) + common_billing_account_path = staticmethod(PolicyTagManagerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PolicyTagManagerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PolicyTagManagerClient.common_folder_path) + parse_common_folder_path = staticmethod(PolicyTagManagerClient.parse_common_folder_path) + common_organization_path = staticmethod(PolicyTagManagerClient.common_organization_path) + parse_common_organization_path = staticmethod(PolicyTagManagerClient.parse_common_organization_path) + common_project_path = staticmethod(PolicyTagManagerClient.common_project_path) + parse_common_project_path = staticmethod(PolicyTagManagerClient.parse_common_project_path) + common_location_path = staticmethod(PolicyTagManagerClient.common_location_path) + parse_common_location_path = staticmethod(PolicyTagManagerClient.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: + PolicyTagManagerAsyncClient: The constructed client. + """ + return PolicyTagManagerClient.from_service_account_info.__func__(PolicyTagManagerAsyncClient, 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: + PolicyTagManagerAsyncClient: The constructed client. + """ + return PolicyTagManagerClient.from_service_account_file.__func__(PolicyTagManagerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyTagManagerTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PolicyTagManagerClient).get_transport_class, type(PolicyTagManagerClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PolicyTagManagerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager 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, ~.PolicyTagManagerTransport]): 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 = PolicyTagManagerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_taxonomy(self, + request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, + *, + parent: str = None, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Creates a taxonomy in a specified project. + The taxonomy is initially empty, that is, it doesn't + contain policy tags. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTaxonomyRequest, dict]): + The request object. Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. + parent (:class:`str`): + Required. Resource name of the + project that the taxonomy will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + taxonomy (:class:`google.cloud.datacatalog_v1.types.Taxonomy`): + The taxonomy to create. + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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, taxonomy]) + if request is 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 = policytagmanager.CreateTaxonomyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if taxonomy is not None: + request.taxonomy = taxonomy + + # 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_taxonomy, + default_timeout=None, + client_info=DEFAULT_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 delete_taxonomy(self, + request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a taxonomy, including all policy tags in this + taxonomy, their associated policies, and the policy tags + references from BigQuery columns. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTaxonomyRequest, dict]): + The request object. Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. + name (:class:`str`): + Required. Resource name of the + taxonomy to delete. + Note: All policy tags in this taxonomy + are also deleted. + + 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 = policytagmanager.DeleteTaxonomyRequest(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_taxonomy, + default_timeout=None, + client_info=DEFAULT_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 update_taxonomy(self, + request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, + *, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Updates a taxonomy, including its display name, + description, and activated policy types. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTaxonomyRequest, dict]): + The request object. Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. + taxonomy (:class:`google.cloud.datacatalog_v1.types.Taxonomy`): + The taxonomy to update. You can + update only its description, display + name, and activated policy types. + + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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([taxonomy]) + if request is 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 = policytagmanager.UpdateTaxonomyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if taxonomy is not None: + request.taxonomy = taxonomy + + # 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_taxonomy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("taxonomy.name", request.taxonomy.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_taxonomies(self, + request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTaxonomiesAsyncPager: + r"""Lists all taxonomies in a project in a particular + location that you have a permission to view. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListTaxonomiesRequest, dict]): + The request object. Request message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + parent (:class:`str`): + Required. Resource name of the + project to list the taxonomies of. + + 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.datacatalog_v1.services.policy_tag_manager.pagers.ListTaxonomiesAsyncPager: + Response message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + + 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 = policytagmanager.ListTaxonomiesRequest(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_taxonomies, + default_timeout=None, + client_info=DEFAULT_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.ListTaxonomiesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_taxonomy(self, + request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Gets a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetTaxonomyRequest, dict]): + The request object. Request message for + [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. + name (:class:`str`): + Required. Resource name of the + taxonomy to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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 = policytagmanager.GetTaxonomyRequest(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_taxonomy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_policy_tag(self, + request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, + *, + parent: str = None, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Creates a policy tag in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreatePolicyTagRequest, dict]): + The request object. Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. + parent (:class:`str`): + Required. Resource name of the + taxonomy that the policy tag will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_tag (:class:`google.cloud.datacatalog_v1.types.PolicyTag`): + The policy tag to create. + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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, policy_tag]) + if request is 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 = policytagmanager.CreatePolicyTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_tag is not None: + request.policy_tag = policy_tag + + # 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_policy_tag, + default_timeout=None, + client_info=DEFAULT_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 delete_policy_tag(self, + request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a policy tag together with the following: + + - All of its descendant policy tags, if any + - Policies associated with the policy tag and its descendants + - References from BigQuery table schema of the policy tag and + its descendants + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeletePolicyTagRequest, dict]): + The request object. Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. + name (:class:`str`): + Required. Resource name of the policy + tag to delete. + Note: All of its descendant policy tags + are also deleted. + + 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 = policytagmanager.DeletePolicyTagRequest(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_policy_tag, + default_timeout=None, + client_info=DEFAULT_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 update_policy_tag(self, + request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, + *, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Updates a policy tag, including its display + name, description, and parent policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdatePolicyTagRequest, dict]): + The request object. Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. + policy_tag (:class:`google.cloud.datacatalog_v1.types.PolicyTag`): + The policy tag to update. You can + update only its description, display + name, and parent policy tag fields. + + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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([policy_tag]) + if request is 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 = policytagmanager.UpdatePolicyTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_tag is not None: + request.policy_tag = policy_tag + + # 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_policy_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("policy_tag.name", request.policy_tag.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_policy_tags(self, + request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPolicyTagsAsyncPager: + r"""Lists all policy tags in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListPolicyTagsRequest, dict]): + The request object. Request message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + parent (:class:`str`): + Required. Resource name of the + taxonomy to list the policy tags of. + + 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.datacatalog_v1.services.policy_tag_manager.pagers.ListPolicyTagsAsyncPager: + Response message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + + 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 = policytagmanager.ListPolicyTagsRequest(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_policy_tags, + default_timeout=None, + client_info=DEFAULT_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.ListPolicyTagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_policy_tag(self, + request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Gets a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetPolicyTagRequest, dict]): + The request object. Request message for + [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. + name (:class:`str`): + Required. Resource name of the policy + tag. + + 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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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 = policytagmanager.GetPolicyTagRequest(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_policy_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a policy tag or a taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy for a policy tag or a taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns your permissions on a specified policy tag or + taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py new file mode 100644 index 00000000..c160511e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py @@ -0,0 +1,1503 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PolicyTagManagerGrpcTransport +from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport + + +class PolicyTagManagerClientMeta(type): + """Metaclass for the PolicyTagManager 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[PolicyTagManagerTransport]] + _transport_registry["grpc"] = PolicyTagManagerGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyTagManagerGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PolicyTagManagerTransport]: + """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 PolicyTagManagerClient(metaclass=PolicyTagManagerClientMeta): + """Policy Tag Manager API service allows you to manage your + policy tags and taxonomies. + + Policy tags are used to tag BigQuery columns and apply + additional access control policies. A taxonomy is a hierarchical + grouping of policy tags that classify data along a common axis. + """ + + @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 = "datacatalog.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: + PolicyTagManagerClient: 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: + PolicyTagManagerClient: 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) -> PolicyTagManagerTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_tag_path(project: str,location: str,taxonomy: str,policy_tag: str,) -> str: + """Returns a fully-qualified policy_tag string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) + + @staticmethod + def parse_policy_tag_path(path: str) -> Dict[str,str]: + """Parses a policy_tag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?P.+?)/policyTags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: + """Returns a fully-qualified taxonomy string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + + @staticmethod + def parse_taxonomy_path(path: str) -> Dict[str,str]: + """Parses a taxonomy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager 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, PolicyTagManagerTransport]): 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, PolicyTagManagerTransport): + # transport is a PolicyTagManagerTransport 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=True, + ) + + def create_taxonomy(self, + request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, + *, + parent: str = None, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Creates a taxonomy in a specified project. + The taxonomy is initially empty, that is, it doesn't + contain policy tags. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreateTaxonomyRequest, dict]): + The request object. Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. + parent (str): + Required. Resource name of the + project that the taxonomy will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): + The taxonomy to create. + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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, taxonomy]) + if request is 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 policytagmanager.CreateTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.CreateTaxonomyRequest): + request = policytagmanager.CreateTaxonomyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if taxonomy is not None: + request.taxonomy = taxonomy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_taxonomy] + + # 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 delete_taxonomy(self, + request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a taxonomy, including all policy tags in this + taxonomy, their associated policies, and the policy tags + references from BigQuery columns. + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeleteTaxonomyRequest, dict]): + The request object. Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. + name (str): + Required. Resource name of the + taxonomy to delete. + Note: All policy tags in this taxonomy + are also deleted. + + 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 policytagmanager.DeleteTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.DeleteTaxonomyRequest): + request = policytagmanager.DeleteTaxonomyRequest(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_taxonomy] + + # Certain fields should be 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 update_taxonomy(self, + request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, + *, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Updates a taxonomy, including its display name, + description, and activated policy types. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdateTaxonomyRequest, dict]): + The request object. Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. + taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): + The taxonomy to update. You can + update only its description, display + name, and activated policy types. + + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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([taxonomy]) + if request is 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 policytagmanager.UpdateTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.UpdateTaxonomyRequest): + request = policytagmanager.UpdateTaxonomyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if taxonomy is not None: + request.taxonomy = taxonomy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_taxonomy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("taxonomy.name", request.taxonomy.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_taxonomies(self, + request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTaxonomiesPager: + r"""Lists all taxonomies in a project in a particular + location that you have a permission to view. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListTaxonomiesRequest, dict]): + The request object. Request message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + parent (str): + Required. Resource name of the + project to list the taxonomies of. + + 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.datacatalog_v1.services.policy_tag_manager.pagers.ListTaxonomiesPager: + Response message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + + 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 policytagmanager.ListTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.ListTaxonomiesRequest): + request = policytagmanager.ListTaxonomiesRequest(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_taxonomies] + + # 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.ListTaxonomiesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_taxonomy(self, + request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Gets a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetTaxonomyRequest, dict]): + The request object. Request message for + [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. + name (str): + Required. Resource name of the + taxonomy to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # 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 policytagmanager.GetTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.GetTaxonomyRequest): + request = policytagmanager.GetTaxonomyRequest(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_taxonomy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_policy_tag(self, + request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, + *, + parent: str = None, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Creates a policy tag in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.CreatePolicyTagRequest, dict]): + The request object. Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. + parent (str): + Required. Resource name of the + taxonomy that the policy tag will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): + The policy tag to create. + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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, policy_tag]) + if request is 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 policytagmanager.CreatePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.CreatePolicyTagRequest): + request = policytagmanager.CreatePolicyTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_tag is not None: + request.policy_tag = policy_tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy_tag] + + # 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 delete_policy_tag(self, + request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a policy tag together with the following: + + - All of its descendant policy tags, if any + - Policies associated with the policy tag and its descendants + - References from BigQuery table schema of the policy tag and + its descendants + + Args: + request (Union[google.cloud.datacatalog_v1.types.DeletePolicyTagRequest, dict]): + The request object. Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. + name (str): + Required. Resource name of the policy + tag to delete. + Note: All of its descendant policy tags + are also deleted. + + 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 policytagmanager.DeletePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.DeletePolicyTagRequest): + request = policytagmanager.DeletePolicyTagRequest(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_policy_tag] + + # Certain fields should be 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 update_policy_tag(self, + request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, + *, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Updates a policy tag, including its display + name, description, and parent policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.UpdatePolicyTagRequest, dict]): + The request object. Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. + policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): + The policy tag to update. You can + update only its description, display + name, and parent policy tag fields. + + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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([policy_tag]) + if request is 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 policytagmanager.UpdatePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.UpdatePolicyTagRequest): + request = policytagmanager.UpdatePolicyTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_tag is not None: + request.policy_tag = policy_tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("policy_tag.name", request.policy_tag.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_policy_tags(self, + request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPolicyTagsPager: + r"""Lists all policy tags in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ListPolicyTagsRequest, dict]): + The request object. Request message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + parent (str): + Required. Resource name of the + taxonomy to list the policy tags of. + + 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.datacatalog_v1.services.policy_tag_manager.pagers.ListPolicyTagsPager: + Response message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + + 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 policytagmanager.ListPolicyTagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.ListPolicyTagsRequest): + request = policytagmanager.ListPolicyTagsRequest(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_policy_tags] + + # 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.ListPolicyTagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_policy_tag(self, + request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Gets a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1.types.GetPolicyTagRequest, dict]): + The request object. Request message for + [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. + name (str): + Required. Resource name of the policy + tag. + + 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.datacatalog_v1.types.PolicyTag: + Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For + example: + + :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` + + Where the "Geolocation" policy tag contains three + children. + + """ + # 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 policytagmanager.GetPolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.GetPolicyTagRequest): + request = policytagmanager.GetPolicyTagRequest(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_policy_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a policy tag or a taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy for a policy tag or a taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns your permissions on a specified policy tag or + taxonomy. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py new file mode 100644 index 00000000..512a1a12 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py @@ -0,0 +1,262 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.datacatalog_v1.types import policytagmanager + + +class ListTaxonomiesPager: + """A pager for iterating through ``list_taxonomies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``taxonomies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTaxonomies`` requests and continue to iterate + through the ``taxonomies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` + 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[..., policytagmanager.ListTaxonomiesResponse], + request: policytagmanager.ListTaxonomiesRequest, + response: policytagmanager.ListTaxonomiesResponse, + *, + 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.datacatalog_v1.types.ListTaxonomiesRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListTaxonomiesResponse): + 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 = policytagmanager.ListTaxonomiesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policytagmanager.ListTaxonomiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[policytagmanager.Taxonomy]: + for page in self.pages: + yield from page.taxonomies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTaxonomiesAsyncPager: + """A pager for iterating through ``list_taxonomies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``taxonomies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTaxonomies`` requests and continue to iterate + through the ``taxonomies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` + 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[policytagmanager.ListTaxonomiesResponse]], + request: policytagmanager.ListTaxonomiesRequest, + response: policytagmanager.ListTaxonomiesResponse, + *, + 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.datacatalog_v1.types.ListTaxonomiesRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListTaxonomiesResponse): + 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 = policytagmanager.ListTaxonomiesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policytagmanager.ListTaxonomiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[policytagmanager.Taxonomy]: + async def async_generator(): + async for page in self.pages: + for response in page.taxonomies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPolicyTagsPager: + """A pager for iterating through ``list_policy_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_tags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicyTags`` requests and continue to iterate + through the ``policy_tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` + 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[..., policytagmanager.ListPolicyTagsResponse], + request: policytagmanager.ListPolicyTagsRequest, + response: policytagmanager.ListPolicyTagsResponse, + *, + 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.datacatalog_v1.types.ListPolicyTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListPolicyTagsResponse): + 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 = policytagmanager.ListPolicyTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policytagmanager.ListPolicyTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[policytagmanager.PolicyTag]: + for page in self.pages: + yield from page.policy_tags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPolicyTagsAsyncPager: + """A pager for iterating through ``list_policy_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_tags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicyTags`` requests and continue to iterate + through the ``policy_tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` + 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[policytagmanager.ListPolicyTagsResponse]], + request: policytagmanager.ListPolicyTagsRequest, + response: policytagmanager.ListPolicyTagsResponse, + *, + 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.datacatalog_v1.types.ListPolicyTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1.types.ListPolicyTagsResponse): + 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 = policytagmanager.ListPolicyTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policytagmanager.ListPolicyTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[policytagmanager.PolicyTag]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_tags: + 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/datacatalog_v1/services/policy_tag_manager/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/__init__.py new file mode 100644 index 00000000..d76a9c05 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/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 PolicyTagManagerTransport +from .grpc import PolicyTagManagerGrpcTransport +from .grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerTransport]] +_transport_registry['grpc'] = PolicyTagManagerGrpcTransport +_transport_registry['grpc_asyncio'] = PolicyTagManagerGrpcAsyncIOTransport + +__all__ = ( + 'PolicyTagManagerTransport', + 'PolicyTagManagerGrpcTransport', + 'PolicyTagManagerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py new file mode 100644 index 00000000..8419877e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py @@ -0,0 +1,317 @@ +# -*- 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 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.datacatalog_v1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PolicyTagManagerTransport(abc.ABC): + """Abstract transport class for PolicyTagManager.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_taxonomy: gapic_v1.method.wrap_method( + self.create_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.delete_taxonomy: gapic_v1.method.wrap_method( + self.delete_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.update_taxonomy: gapic_v1.method.wrap_method( + self.update_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.list_taxonomies: gapic_v1.method.wrap_method( + self.list_taxonomies, + default_timeout=None, + client_info=client_info, + ), + self.get_taxonomy: gapic_v1.method.wrap_method( + self.get_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.create_policy_tag: gapic_v1.method.wrap_method( + self.create_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_policy_tag: gapic_v1.method.wrap_method( + self.delete_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.update_policy_tag: gapic_v1.method.wrap_method( + self.update_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.list_policy_tags: gapic_v1.method.wrap_method( + self.list_policy_tags, + default_timeout=None, + client_info=client_info, + ), + self.get_policy_tag: gapic_v1.method.wrap_method( + self.get_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + Union[ + policytagmanager.ListTaxonomiesResponse, + Awaitable[policytagmanager.ListTaxonomiesResponse] + ]]: + raise NotImplementedError() + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + Union[ + policytagmanager.ListPolicyTagsResponse, + Awaitable[policytagmanager.ListPolicyTagsResponse] + ]]: + raise NotImplementedError() + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PolicyTagManagerTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py new file mode 100644 index 00000000..5d8abd85 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py @@ -0,0 +1,587 @@ +# -*- 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.datacatalog_v1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO + + +class PolicyTagManagerGrpcTransport(PolicyTagManagerTransport): + """gRPC backend transport for PolicyTagManager. + + Policy Tag Manager API service allows you to manage your + policy tags and taxonomies. + + Policy tags are used to tag BigQuery columns and apply + additional access control policies. A taxonomy is a hierarchical + grouping of policy tags that classify data along a common axis. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the create taxonomy method over gRPC. + + Creates a taxonomy in a specified project. + The taxonomy is initially empty, that is, it doesn't + contain policy tags. + + Returns: + Callable[[~.CreateTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/CreateTaxonomy', + request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['create_taxonomy'] + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete taxonomy method over gRPC. + + Deletes a taxonomy, including all policy tags in this + taxonomy, their associated policies, and the policy tags + references from BigQuery columns. + + Returns: + Callable[[~.DeleteTaxonomyRequest], + ~.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_taxonomy' not in self._stubs: + self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/DeleteTaxonomy', + request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_taxonomy'] + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the update taxonomy method over gRPC. + + Updates a taxonomy, including its display name, + description, and activated policy types. + + Returns: + Callable[[~.UpdateTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/UpdateTaxonomy', + request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['update_taxonomy'] + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + policytagmanager.ListTaxonomiesResponse]: + r"""Return a callable for the list taxonomies method over gRPC. + + Lists all taxonomies in a project in a particular + location that you have a permission to view. + + Returns: + Callable[[~.ListTaxonomiesRequest], + ~.ListTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: + self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/ListTaxonomies', + request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, + response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, + ) + return self._stubs['list_taxonomies'] + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the get taxonomy method over gRPC. + + Gets a taxonomy. + + Returns: + Callable[[~.GetTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetTaxonomy', + request_serializer=policytagmanager.GetTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['get_taxonomy'] + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the create policy tag method over gRPC. + + Creates a policy tag in a taxonomy. + + Returns: + Callable[[~.CreatePolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/CreatePolicyTag', + request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['create_policy_tag'] + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete policy tag method over gRPC. + + Deletes a policy tag together with the following: + + - All of its descendant policy tags, if any + - Policies associated with the policy tag and its descendants + - References from BigQuery table schema of the policy tag and + its descendants + + Returns: + Callable[[~.DeletePolicyTagRequest], + ~.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_policy_tag' not in self._stubs: + self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/DeletePolicyTag', + request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_policy_tag'] + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the update policy tag method over gRPC. + + Updates a policy tag, including its display + name, description, and parent policy tag. + + Returns: + Callable[[~.UpdatePolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/UpdatePolicyTag', + request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['update_policy_tag'] + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + policytagmanager.ListPolicyTagsResponse]: + r"""Return a callable for the list policy tags method over gRPC. + + Lists all policy tags in a taxonomy. + + Returns: + Callable[[~.ListPolicyTagsRequest], + ~.ListPolicyTagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: + self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/ListPolicyTags', + request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, + response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, + ) + return self._stubs['list_policy_tags'] + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the get policy tag method over gRPC. + + Gets a policy tag. + + Returns: + Callable[[~.GetPolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetPolicyTag', + request_serializer=policytagmanager.GetPolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['get_policy_tag'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a policy tag or a taxonomy. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy for a policy tag or a taxonomy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns your permissions on a specified policy tag or + taxonomy. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'PolicyTagManagerGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py new file mode 100644 index 00000000..e5ffff41 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py @@ -0,0 +1,591 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .grpc import PolicyTagManagerGrpcTransport + + +class PolicyTagManagerGrpcAsyncIOTransport(PolicyTagManagerTransport): + """gRPC AsyncIO backend transport for PolicyTagManager. + + Policy Tag Manager API service allows you to manage your + policy tags and taxonomies. + + Policy tags are used to tag BigQuery columns and apply + additional access control policies. A taxonomy is a hierarchical + grouping of policy tags that classify data along a common axis. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the create taxonomy method over gRPC. + + Creates a taxonomy in a specified project. + The taxonomy is initially empty, that is, it doesn't + contain policy tags. + + Returns: + Callable[[~.CreateTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/CreateTaxonomy', + request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['create_taxonomy'] + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete taxonomy method over gRPC. + + Deletes a taxonomy, including all policy tags in this + taxonomy, their associated policies, and the policy tags + references from BigQuery columns. + + Returns: + Callable[[~.DeleteTaxonomyRequest], + 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_taxonomy' not in self._stubs: + self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/DeleteTaxonomy', + request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_taxonomy'] + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the update taxonomy method over gRPC. + + Updates a taxonomy, including its display name, + description, and activated policy types. + + Returns: + Callable[[~.UpdateTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/UpdateTaxonomy', + request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['update_taxonomy'] + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + Awaitable[policytagmanager.ListTaxonomiesResponse]]: + r"""Return a callable for the list taxonomies method over gRPC. + + Lists all taxonomies in a project in a particular + location that you have a permission to view. + + Returns: + Callable[[~.ListTaxonomiesRequest], + Awaitable[~.ListTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: + self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/ListTaxonomies', + request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, + response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, + ) + return self._stubs['list_taxonomies'] + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the get taxonomy method over gRPC. + + Gets a taxonomy. + + Returns: + Callable[[~.GetTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetTaxonomy', + request_serializer=policytagmanager.GetTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['get_taxonomy'] + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the create policy tag method over gRPC. + + Creates a policy tag in a taxonomy. + + Returns: + Callable[[~.CreatePolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/CreatePolicyTag', + request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['create_policy_tag'] + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete policy tag method over gRPC. + + Deletes a policy tag together with the following: + + - All of its descendant policy tags, if any + - Policies associated with the policy tag and its descendants + - References from BigQuery table schema of the policy tag and + its descendants + + Returns: + Callable[[~.DeletePolicyTagRequest], + 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_policy_tag' not in self._stubs: + self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/DeletePolicyTag', + request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_policy_tag'] + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the update policy tag method over gRPC. + + Updates a policy tag, including its display + name, description, and parent policy tag. + + Returns: + Callable[[~.UpdatePolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/UpdatePolicyTag', + request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['update_policy_tag'] + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + Awaitable[policytagmanager.ListPolicyTagsResponse]]: + r"""Return a callable for the list policy tags method over gRPC. + + Lists all policy tags in a taxonomy. + + Returns: + Callable[[~.ListPolicyTagsRequest], + Awaitable[~.ListPolicyTagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: + self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/ListPolicyTags', + request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, + response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, + ) + return self._stubs['list_policy_tags'] + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the get policy tag method over gRPC. + + Gets a policy tag. + + Returns: + Callable[[~.GetPolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetPolicyTag', + request_serializer=policytagmanager.GetPolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['get_policy_tag'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a policy tag or a taxonomy. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy for a policy tag or a taxonomy. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns your permissions on a specified policy tag or + taxonomy. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PolicyTagManagerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py new file mode 100644 index 00000000..5e73ed2a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__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 PolicyTagManagerSerializationClient +from .async_client import PolicyTagManagerSerializationAsyncClient + +__all__ = ( + 'PolicyTagManagerSerializationClient', + 'PolicyTagManagerSerializationAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py new file mode 100644 index 00000000..4ae79e6e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py @@ -0,0 +1,372 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization +from google.cloud.datacatalog_v1.types import timestamps +from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport +from .client import PolicyTagManagerSerializationClient + + +class PolicyTagManagerSerializationAsyncClient: + """Policy Tag Manager Serialization API service allows you to + manipulate your policy tags and taxonomies in a serialized + format. + Taxonomy is a hierarchical group of policy tags. + """ + + _client: PolicyTagManagerSerializationClient + + DEFAULT_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_MTLS_ENDPOINT + + taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.taxonomy_path) + parse_taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.parse_taxonomy_path) + common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PolicyTagManagerSerializationClient.common_folder_path) + parse_common_folder_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_folder_path) + common_organization_path = staticmethod(PolicyTagManagerSerializationClient.common_organization_path) + parse_common_organization_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_organization_path) + common_project_path = staticmethod(PolicyTagManagerSerializationClient.common_project_path) + parse_common_project_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_project_path) + common_location_path = staticmethod(PolicyTagManagerSerializationClient.common_location_path) + parse_common_location_path = staticmethod(PolicyTagManagerSerializationClient.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: + PolicyTagManagerSerializationAsyncClient: The constructed client. + """ + return PolicyTagManagerSerializationClient.from_service_account_info.__func__(PolicyTagManagerSerializationAsyncClient, 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: + PolicyTagManagerSerializationAsyncClient: The constructed client. + """ + return PolicyTagManagerSerializationClient.from_service_account_file.__func__(PolicyTagManagerSerializationAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyTagManagerSerializationTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerSerializationTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PolicyTagManagerSerializationClient).get_transport_class, type(PolicyTagManagerSerializationClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PolicyTagManagerSerializationTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager serialization 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, ~.PolicyTagManagerSerializationTransport]): 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 = PolicyTagManagerSerializationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def replace_taxonomy(self, + request: Union[policytagmanagerserialization.ReplaceTaxonomyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Replaces (updates) a taxonomy and all its policy tags. + + The taxonomy and its entire hierarchy of policy tags must be + represented literally by ``SerializedTaxonomy`` and the nested + ``SerializedPolicyTag`` messages. + + This operation automatically does the following: + + - Deletes the existing policy tags that are missing from the + ``SerializedPolicyTag``. + - Creates policy tags that don't have resource names. They are + considered new. + - Updates policy tags with valid resources names accordingly. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ReplaceTaxonomyRequest, dict]): + The request object. Request message for + [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # Create or coerce a protobuf request object. + request = policytagmanagerserialization.ReplaceTaxonomyRequest(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.replace_taxonomy, + default_timeout=None, + client_info=DEFAULT_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 import_taxonomies(self, + request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ImportTaxonomiesResponse: + r"""Creates new taxonomies (including their policy tags) + in a given project by importing from inlined or cross- + regional sources. + For a cross-regional source, new taxonomies are created + by copying from a source in another region. + + For an inlined source, taxonomies and policy tags are + created in bulk using nested protocol buffer structures. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ImportTaxonomiesRequest, dict]): + The request object. Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.ImportTaxonomiesResponse: + Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + request = policytagmanagerserialization.ImportTaxonomiesRequest(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.import_taxonomies, + default_timeout=None, + client_info=DEFAULT_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 export_taxonomies(self, + request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ExportTaxonomiesResponse: + r"""Exports taxonomies in the requested type and returns them, + including their policy tags. The requested taxonomies must + belong to the same project. + + This method generates ``SerializedTaxonomy`` protocol buffers + with nested policy tags that can be used as input for + ``ImportTaxonomies`` calls. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ExportTaxonomiesRequest, dict]): + The request object. Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.ExportTaxonomiesResponse: + Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + request = policytagmanagerserialization.ExportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_taxonomies, + default_timeout=None, + client_info=DEFAULT_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 __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerSerializationAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py new file mode 100644 index 00000000..898822f7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py @@ -0,0 +1,572 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization +from google.cloud.datacatalog_v1.types import timestamps +from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PolicyTagManagerSerializationGrpcTransport +from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport + + +class PolicyTagManagerSerializationClientMeta(type): + """Metaclass for the PolicyTagManagerSerialization 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[PolicyTagManagerSerializationTransport]] + _transport_registry["grpc"] = PolicyTagManagerSerializationGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyTagManagerSerializationGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PolicyTagManagerSerializationTransport]: + """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 PolicyTagManagerSerializationClient(metaclass=PolicyTagManagerSerializationClientMeta): + """Policy Tag Manager Serialization API service allows you to + manipulate your policy tags and taxonomies in a serialized + format. + Taxonomy is a hierarchical group of policy tags. + """ + + @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 = "datacatalog.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: + PolicyTagManagerSerializationClient: 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: + PolicyTagManagerSerializationClient: 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) -> PolicyTagManagerSerializationTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerSerializationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: + """Returns a fully-qualified taxonomy string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + + @staticmethod + def parse_taxonomy_path(path: str) -> Dict[str,str]: + """Parses a taxonomy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerSerializationTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager serialization 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, PolicyTagManagerSerializationTransport]): 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, PolicyTagManagerSerializationTransport): + # transport is a PolicyTagManagerSerializationTransport 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=True, + ) + + def replace_taxonomy(self, + request: Union[policytagmanagerserialization.ReplaceTaxonomyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Replaces (updates) a taxonomy and all its policy tags. + + The taxonomy and its entire hierarchy of policy tags must be + represented literally by ``SerializedTaxonomy`` and the nested + ``SerializedPolicyTag`` messages. + + This operation automatically does the following: + + - Deletes the existing policy tags that are missing from the + ``SerializedPolicyTag``. + - Creates policy tags that don't have resource names. They are + considered new. + - Updates policy tags with valid resources names accordingly. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ReplaceTaxonomyRequest, dict]): + The request object. Request message for + [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.Taxonomy: + A taxonomy is a collection of hierarchical policy tags that classify data + along a common axis. + + For example, a "data sensitivity" taxonomy might + contain the following policy tags: + + :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` + + A "data origin" taxonomy might contain the following + policy tags: + + :literal:`\` + User data + Employee data + Partner data + Public data`\ \` + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a policytagmanagerserialization.ReplaceTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanagerserialization.ReplaceTaxonomyRequest): + request = policytagmanagerserialization.ReplaceTaxonomyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_taxonomy] + + # Certain fields should be 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 import_taxonomies(self, + request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ImportTaxonomiesResponse: + r"""Creates new taxonomies (including their policy tags) + in a given project by importing from inlined or cross- + regional sources. + For a cross-regional source, new taxonomies are created + by copying from a source in another region. + + For an inlined source, taxonomies and policy tags are + created in bulk using nested protocol buffer structures. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ImportTaxonomiesRequest, dict]): + The request object. Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.ImportTaxonomiesResponse: + Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a policytagmanagerserialization.ImportTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanagerserialization.ImportTaxonomiesRequest): + request = policytagmanagerserialization.ImportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_taxonomies] + + # 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 export_taxonomies(self, + request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ExportTaxonomiesResponse: + r"""Exports taxonomies in the requested type and returns them, + including their policy tags. The requested taxonomies must + belong to the same project. + + This method generates ``SerializedTaxonomy`` protocol buffers + with nested policy tags that can be used as input for + ``ImportTaxonomies`` calls. + + Args: + request (Union[google.cloud.datacatalog_v1.types.ExportTaxonomiesRequest, dict]): + The request object. Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1.types.ExportTaxonomiesResponse: + Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a policytagmanagerserialization.ExportTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanagerserialization.ExportTaxonomiesRequest): + request = policytagmanagerserialization.ExportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_taxonomies] + + # 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerSerializationClient", +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py new file mode 100644 index 00000000..2864dab0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/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 PolicyTagManagerSerializationTransport +from .grpc import PolicyTagManagerSerializationGrpcTransport +from .grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerSerializationTransport]] +_transport_registry['grpc'] = PolicyTagManagerSerializationGrpcTransport +_transport_registry['grpc_asyncio'] = PolicyTagManagerSerializationGrpcAsyncIOTransport + +__all__ = ( + 'PolicyTagManagerSerializationTransport', + 'PolicyTagManagerSerializationGrpcTransport', + 'PolicyTagManagerSerializationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py new file mode 100644 index 00000000..2bf138ba --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py @@ -0,0 +1,175 @@ +# -*- 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 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.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PolicyTagManagerSerializationTransport(abc.ABC): + """Abstract transport class for PolicyTagManagerSerialization.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.replace_taxonomy: gapic_v1.method.wrap_method( + self.replace_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.import_taxonomies: gapic_v1.method.wrap_method( + self.import_taxonomies, + default_timeout=None, + client_info=client_info, + ), + self.export_taxonomies: gapic_v1.method.wrap_method( + self.export_taxonomies, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def replace_taxonomy(self) -> Callable[ + [policytagmanagerserialization.ReplaceTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + Union[ + policytagmanagerserialization.ImportTaxonomiesResponse, + Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse] + ]]: + raise NotImplementedError() + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + Union[ + policytagmanagerserialization.ExportTaxonomiesResponse, + Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PolicyTagManagerSerializationTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py new file mode 100644 index 00000000..5255af94 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py @@ -0,0 +1,335 @@ +# -*- 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.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization +from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO + + +class PolicyTagManagerSerializationGrpcTransport(PolicyTagManagerSerializationTransport): + """gRPC backend transport for PolicyTagManagerSerialization. + + Policy Tag Manager Serialization API service allows you to + manipulate your policy tags and taxonomies in a serialized + format. + Taxonomy is a hierarchical group of policy tags. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 replace_taxonomy(self) -> Callable[ + [policytagmanagerserialization.ReplaceTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the replace taxonomy method over gRPC. + + Replaces (updates) a taxonomy and all its policy tags. + + The taxonomy and its entire hierarchy of policy tags must be + represented literally by ``SerializedTaxonomy`` and the nested + ``SerializedPolicyTag`` messages. + + This operation automatically does the following: + + - Deletes the existing policy tags that are missing from the + ``SerializedPolicyTag``. + - Creates policy tags that don't have resource names. They are + considered new. + - Updates policy tags with valid resources names accordingly. + + Returns: + Callable[[~.ReplaceTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_taxonomy' not in self._stubs: + self._stubs['replace_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ReplaceTaxonomy', + request_serializer=policytagmanagerserialization.ReplaceTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['replace_taxonomy'] + + @property + def import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + policytagmanagerserialization.ImportTaxonomiesResponse]: + r"""Return a callable for the import taxonomies method over gRPC. + + Creates new taxonomies (including their policy tags) + in a given project by importing from inlined or cross- + regional sources. + For a cross-regional source, new taxonomies are created + by copying from a source in another region. + + For an inlined source, taxonomies and policy tags are + created in bulk using nested protocol buffer structures. + + Returns: + Callable[[~.ImportTaxonomiesRequest], + ~.ImportTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_taxonomies' not in self._stubs: + self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ImportTaxonomies', + request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, + ) + return self._stubs['import_taxonomies'] + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + policytagmanagerserialization.ExportTaxonomiesResponse]: + r"""Return a callable for the export taxonomies method over gRPC. + + Exports taxonomies in the requested type and returns them, + including their policy tags. The requested taxonomies must + belong to the same project. + + This method generates ``SerializedTaxonomy`` protocol buffers + with nested policy tags that can be used as input for + ``ImportTaxonomies`` calls. + + Returns: + Callable[[~.ExportTaxonomiesRequest], + ~.ExportTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_taxonomies' not in self._stubs: + self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ExportTaxonomies', + request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, + ) + return self._stubs['export_taxonomies'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'PolicyTagManagerSerializationGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py new file mode 100644 index 00000000..3291686e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py @@ -0,0 +1,339 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization +from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .grpc import PolicyTagManagerSerializationGrpcTransport + + +class PolicyTagManagerSerializationGrpcAsyncIOTransport(PolicyTagManagerSerializationTransport): + """gRPC AsyncIO backend transport for PolicyTagManagerSerialization. + + Policy Tag Manager Serialization API service allows you to + manipulate your policy tags and taxonomies in a serialized + format. + Taxonomy is a hierarchical group of policy tags. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 replace_taxonomy(self) -> Callable[ + [policytagmanagerserialization.ReplaceTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the replace taxonomy method over gRPC. + + Replaces (updates) a taxonomy and all its policy tags. + + The taxonomy and its entire hierarchy of policy tags must be + represented literally by ``SerializedTaxonomy`` and the nested + ``SerializedPolicyTag`` messages. + + This operation automatically does the following: + + - Deletes the existing policy tags that are missing from the + ``SerializedPolicyTag``. + - Creates policy tags that don't have resource names. They are + considered new. + - Updates policy tags with valid resources names accordingly. + + Returns: + Callable[[~.ReplaceTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'replace_taxonomy' not in self._stubs: + self._stubs['replace_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ReplaceTaxonomy', + request_serializer=policytagmanagerserialization.ReplaceTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['replace_taxonomy'] + + @property + def import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse]]: + r"""Return a callable for the import taxonomies method over gRPC. + + Creates new taxonomies (including their policy tags) + in a given project by importing from inlined or cross- + regional sources. + For a cross-regional source, new taxonomies are created + by copying from a source in another region. + + For an inlined source, taxonomies and policy tags are + created in bulk using nested protocol buffer structures. + + Returns: + Callable[[~.ImportTaxonomiesRequest], + Awaitable[~.ImportTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_taxonomies' not in self._stubs: + self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ImportTaxonomies', + request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, + ) + return self._stubs['import_taxonomies'] + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse]]: + r"""Return a callable for the export taxonomies method over gRPC. + + Exports taxonomies in the requested type and returns them, + including their policy tags. The requested taxonomies must + belong to the same project. + + This method generates ``SerializedTaxonomy`` protocol buffers + with nested policy tags that can be used as input for + ``ImportTaxonomies`` calls. + + Returns: + Callable[[~.ExportTaxonomiesRequest], + Awaitable[~.ExportTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_taxonomies' not in self._stubs: + self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ExportTaxonomies', + request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, + ) + return self._stubs['export_taxonomies'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PolicyTagManagerSerializationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py new file mode 100644 index 00000000..d9d6c548 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py @@ -0,0 +1,205 @@ +# -*- 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 .bigquery import ( + BigQueryConnectionSpec, + BigQueryRoutineSpec, + CloudSqlBigQueryConnectionSpec, +) +from .data_source import ( + DataSource, +) +from .datacatalog import ( + CreateEntryGroupRequest, + CreateEntryRequest, + CreateTagRequest, + CreateTagTemplateFieldRequest, + CreateTagTemplateRequest, + DatabaseTableSpec, + DataSourceConnectionSpec, + DeleteEntryGroupRequest, + DeleteEntryRequest, + DeleteTagRequest, + DeleteTagTemplateFieldRequest, + DeleteTagTemplateRequest, + Entry, + EntryGroup, + GetEntryGroupRequest, + GetEntryRequest, + GetTagTemplateRequest, + ListEntriesRequest, + ListEntriesResponse, + ListEntryGroupsRequest, + ListEntryGroupsResponse, + ListTagsRequest, + ListTagsResponse, + LookupEntryRequest, + RenameTagTemplateFieldEnumValueRequest, + RenameTagTemplateFieldRequest, + RoutineSpec, + SearchCatalogRequest, + SearchCatalogResponse, + UpdateEntryGroupRequest, + UpdateEntryRequest, + UpdateTagRequest, + UpdateTagTemplateFieldRequest, + UpdateTagTemplateRequest, + EntryType, +) +from .gcs_fileset_spec import ( + GcsFilesetSpec, + GcsFileSpec, +) +from .policytagmanager import ( + CreatePolicyTagRequest, + CreateTaxonomyRequest, + DeletePolicyTagRequest, + DeleteTaxonomyRequest, + GetPolicyTagRequest, + GetTaxonomyRequest, + ListPolicyTagsRequest, + ListPolicyTagsResponse, + ListTaxonomiesRequest, + ListTaxonomiesResponse, + PolicyTag, + Taxonomy, + UpdatePolicyTagRequest, + UpdateTaxonomyRequest, +) +from .policytagmanagerserialization import ( + CrossRegionalSource, + ExportTaxonomiesRequest, + ExportTaxonomiesResponse, + ImportTaxonomiesRequest, + ImportTaxonomiesResponse, + InlineSource, + ReplaceTaxonomyRequest, + SerializedPolicyTag, + SerializedTaxonomy, +) +from .schema import ( + ColumnSchema, + Schema, +) +from .search import ( + SearchCatalogResult, + SearchResultType, +) +from .table_spec import ( + BigQueryDateShardedSpec, + BigQueryTableSpec, + TableSpec, + ViewSpec, + TableSourceType, +) +from .tags import ( + FieldType, + Tag, + TagField, + TagTemplate, + TagTemplateField, +) +from .timestamps import ( + SystemTimestamps, +) +from .usage import ( + UsageSignal, + UsageStats, +) + +__all__ = ( + 'BigQueryConnectionSpec', + 'BigQueryRoutineSpec', + 'CloudSqlBigQueryConnectionSpec', + 'IntegratedSystem', + 'DataSource', + 'CreateEntryGroupRequest', + 'CreateEntryRequest', + 'CreateTagRequest', + 'CreateTagTemplateFieldRequest', + 'CreateTagTemplateRequest', + 'DatabaseTableSpec', + 'DataSourceConnectionSpec', + 'DeleteEntryGroupRequest', + 'DeleteEntryRequest', + 'DeleteTagRequest', + 'DeleteTagTemplateFieldRequest', + 'DeleteTagTemplateRequest', + 'Entry', + 'EntryGroup', + 'GetEntryGroupRequest', + 'GetEntryRequest', + 'GetTagTemplateRequest', + 'ListEntriesRequest', + 'ListEntriesResponse', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'ListTagsRequest', + 'ListTagsResponse', + 'LookupEntryRequest', + 'RenameTagTemplateFieldEnumValueRequest', + 'RenameTagTemplateFieldRequest', + 'RoutineSpec', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'UpdateEntryGroupRequest', + 'UpdateEntryRequest', + 'UpdateTagRequest', + 'UpdateTagTemplateFieldRequest', + 'UpdateTagTemplateRequest', + 'EntryType', + 'GcsFilesetSpec', + 'GcsFileSpec', + 'CreatePolicyTagRequest', + 'CreateTaxonomyRequest', + 'DeletePolicyTagRequest', + 'DeleteTaxonomyRequest', + 'GetPolicyTagRequest', + 'GetTaxonomyRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'PolicyTag', + 'Taxonomy', + 'UpdatePolicyTagRequest', + 'UpdateTaxonomyRequest', + 'CrossRegionalSource', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + 'ImportTaxonomiesRequest', + 'ImportTaxonomiesResponse', + 'InlineSource', + 'ReplaceTaxonomyRequest', + 'SerializedPolicyTag', + 'SerializedTaxonomy', + 'ColumnSchema', + 'Schema', + 'SearchCatalogResult', + 'SearchResultType', + 'BigQueryDateShardedSpec', + 'BigQueryTableSpec', + 'TableSpec', + 'ViewSpec', + 'TableSourceType', + 'FieldType', + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'SystemTimestamps', + 'UsageSignal', + 'UsageStats', +) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py new file mode 100644 index 00000000..ab7ba45a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py @@ -0,0 +1,115 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'BigQueryConnectionSpec', + 'CloudSqlBigQueryConnectionSpec', + 'BigQueryRoutineSpec', + }, +) + + +class BigQueryConnectionSpec(proto.Message): + r"""Specification for the BigQuery connection. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + connection_type (google.cloud.datacatalog_v1.types.BigQueryConnectionSpec.ConnectionType): + The type of the BigQuery connection. + cloud_sql (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec): + Specification for the BigQuery connection to + a Cloud SQL instance. + This field is a member of `oneof`_ ``connection_spec``. + has_credential (bool): + True if there are credentials attached to the + BigQuery connection; false otherwise. + """ + class ConnectionType(proto.Enum): + r"""The type of the BigQuery connection.""" + CONNECTION_TYPE_UNSPECIFIED = 0 + CLOUD_SQL = 1 + + connection_type = proto.Field( + proto.ENUM, + number=1, + enum=ConnectionType, + ) + cloud_sql = proto.Field( + proto.MESSAGE, + number=2, + oneof='connection_spec', + message='CloudSqlBigQueryConnectionSpec', + ) + has_credential = proto.Field( + proto.BOOL, + number=3, + ) + + +class CloudSqlBigQueryConnectionSpec(proto.Message): + r"""Specification for the BigQuery connection to a Cloud SQL + instance. + + Attributes: + instance_id (str): + Cloud SQL instance ID in the format of + ``project:location:instance``. + database (str): + Database name. + type_ (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec.DatabaseType): + Type of the Cloud SQL database. + """ + class DatabaseType(proto.Enum): + r"""Supported Cloud SQL database types.""" + DATABASE_TYPE_UNSPECIFIED = 0 + POSTGRES = 1 + MYSQL = 2 + + instance_id = proto.Field( + proto.STRING, + number=1, + ) + database = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=DatabaseType, + ) + + +class BigQueryRoutineSpec(proto.Message): + r"""Fields specific for BigQuery routines. + + Attributes: + imported_libraries (Sequence[str]): + Paths of the imported libraries. + """ + + imported_libraries = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py new file mode 100644 index 00000000..60d41442 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py @@ -0,0 +1,37 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'IntegratedSystem', + }, +) + + +class IntegratedSystem(proto.Enum): + r"""This enum lists all the systems that Data Catalog integrates + with. + """ + INTEGRATED_SYSTEM_UNSPECIFIED = 0 + BIGQUERY = 1 + CLOUD_PUBSUB = 2 + DATAPROC_METASTORE = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py new file mode 100644 index 00000000..2506054d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py @@ -0,0 +1,56 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'DataSource', + }, +) + + +class DataSource(proto.Message): + r"""Physical location of an entry. + + Attributes: + service (google.cloud.datacatalog_v1.types.DataSource.Service): + Service that physically stores the data. + resource (str): + Full name of a resource as defined by the service. For + example: + + ``//bigquery.googleapis.com/projects/{PROJECT_ID}/locations/{LOCATION}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` + """ + class Service(proto.Enum): + r"""Name of a service that stores the data.""" + SERVICE_UNSPECIFIED = 0 + CLOUD_STORAGE = 1 + BIGQUERY = 2 + + service = proto.Field( + proto.ENUM, + number=1, + enum=Service, + ) + resource = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py new file mode 100644 index 00000000..8fb5604a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py @@ -0,0 +1,1578 @@ +# -*- 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.datacatalog_v1.types import bigquery +from google.cloud.datacatalog_v1.types import common +from google.cloud.datacatalog_v1.types import data_source as gcd_data_source +from google.cloud.datacatalog_v1.types import gcs_fileset_spec as gcd_gcs_fileset_spec +from google.cloud.datacatalog_v1.types import schema as gcd_schema +from google.cloud.datacatalog_v1.types import search +from google.cloud.datacatalog_v1.types import table_spec +from google.cloud.datacatalog_v1.types import tags as gcd_tags +from google.cloud.datacatalog_v1.types import timestamps +from google.cloud.datacatalog_v1.types import usage +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'EntryType', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'CreateEntryGroupRequest', + 'UpdateEntryGroupRequest', + 'GetEntryGroupRequest', + 'DeleteEntryGroupRequest', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'CreateEntryRequest', + 'UpdateEntryRequest', + 'DeleteEntryRequest', + 'GetEntryRequest', + 'LookupEntryRequest', + 'Entry', + 'DatabaseTableSpec', + 'DataSourceConnectionSpec', + 'RoutineSpec', + 'EntryGroup', + 'CreateTagTemplateRequest', + 'GetTagTemplateRequest', + 'UpdateTagTemplateRequest', + 'DeleteTagTemplateRequest', + 'CreateTagRequest', + 'UpdateTagRequest', + 'DeleteTagRequest', + 'CreateTagTemplateFieldRequest', + 'UpdateTagTemplateFieldRequest', + 'RenameTagTemplateFieldRequest', + 'RenameTagTemplateFieldEnumValueRequest', + 'DeleteTagTemplateFieldRequest', + 'ListTagsRequest', + 'ListTagsResponse', + 'ListEntriesRequest', + 'ListEntriesResponse', + }, +) + + +class EntryType(proto.Enum): + r"""The enum field that lists all the types of entry resources in Data + Catalog. For example, a BigQuery table entry has the ``TABLE`` type. + """ + ENTRY_TYPE_UNSPECIFIED = 0 + TABLE = 2 + MODEL = 5 + DATA_STREAM = 3 + FILESET = 4 + CLUSTER = 6 + DATABASE = 7 + DATA_SOURCE_CONNECTION = 8 + ROUTINE = 9 + SERVICE = 14 + + +class SearchCatalogRequest(proto.Message): + r"""Request message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Attributes: + scope (google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope): + Required. The scope of this search request. + + The ``scope`` is invalid if ``include_org_ids``, + ``include_project_ids`` are empty AND + ``include_gcp_public_datasets`` is set to ``false``. In this + case, the request returns an error. + query (str): + Optional. The query string with a minimum of 3 characters + and specific syntax. For more information, see `Data Catalog + search + syntax `__. + + An empty query string returns all data assets (in the + specified scope) that you have access to. + + A query string can be a simple ``xyz`` or qualified by + predicates: + + - ``name:x`` + - ``column:y`` + - ``description:z`` + page_size (int): + Number of results to return in a single + search page. + Can't be negative or 0, defaults to 10 in this + case. The maximum number is 1000. If exceeded, + throws an "invalid argument" exception. + page_token (str): + Optional. Pagination token that, if specified, returns the + next page of search results. If empty, returns the first + page. + + This token is returned in the + [SearchCatalogResponse.next_page_token][google.cloud.datacatalog.v1.SearchCatalogResponse.next_page_token] + field of the response to a previous + [SearchCatalogRequest][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog] + call. + order_by (str): + Specifies the order of results. + + Currently supported case-sensitive values are: + + - ``relevance`` that can only be descending + - ``last_modified_timestamp [asc|desc]`` with descending + (``desc``) as default + + If this parameter is omitted, it defaults to the descending + ``relevance``. + """ + + class Scope(proto.Message): + r"""The criteria that select the subspace used for query + matching. + + Attributes: + include_org_ids (Sequence[str]): + The list of organization IDs to search within. + + To find your organization ID, follow the steps from + [Creating and managing organizations] + (/resource-manager/docs/creating-managing-organization). + include_project_ids (Sequence[str]): + The list of project IDs to search within. + + For more information on the distinction between project + names, IDs, and numbers, see + `Projects `__. + include_gcp_public_datasets (bool): + If ``true``, include Google Cloud Platform (GCP) public + datasets in search results. By default, they are excluded. + + See `Google Cloud Public Datasets `__ for + more information. + restricted_locations (Sequence[str]): + Optional. The list of locations to search within. If empty, + all locations are searched. + + Returns an error if any location in the list isn't one of + the `Supported + regions `__. + + If a location is unreachable, its name is returned in the + ``SearchCatalogResponse.unreachable`` field. To get + additional information on the error, repeat the search + request and set the location name as the value of this + parameter. + include_public_tag_templates (bool): + Optional. If ``true``, include [public tag + templates][google.cloud.datacatalog.v1.TagTemplate.is_publicly_readable] + in the search results. By default, they are included only if + you have explicit permissions on them to view them. For + example, if you are the owner. + + Other scope fields, for example, ``include_org_ids``, still + restrict the returned public tag templates and at least one + of them is required. + """ + + include_org_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + include_project_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + include_gcp_public_datasets = proto.Field( + proto.BOOL, + number=7, + ) + restricted_locations = proto.RepeatedField( + proto.STRING, + number=16, + ) + include_public_tag_templates = proto.Field( + proto.BOOL, + number=19, + ) + + scope = proto.Field( + proto.MESSAGE, + number=6, + message=Scope, + ) + query = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class SearchCatalogResponse(proto.Message): + r"""Response message for + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + + Attributes: + results (Sequence[google.cloud.datacatalog_v1.types.SearchCatalogResult]): + Search results. + next_page_token (str): + Pagination token that can be used in + subsequent calls to retrieve the next page of + results. + unreachable (Sequence[str]): + Unreachable locations. Search results don't include data + from those locations. + + To get additional information on an error, repeat the search + request and restrict it to specific locations by setting the + ``SearchCatalogRequest.scope.restricted_locations`` + parameter. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=search.SearchCatalogResult, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class CreateEntryGroupRequest(proto.Message): + r"""Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. + + Attributes: + parent (str): + Required. The names of the project and + location that the new entry group belongs to. + Note: The entry group itself and its child + resources might not be stored in the location + specified in its name. + entry_group_id (str): + Required. The ID of the entry group to create. + + The ID must contain only letters (a-z, A-Z), numbers (0-9), + underscores (_), and must start with a letter or underscore. + The maximum size is 64 bytes when encoded in UTF-8. + entry_group (google.cloud.datacatalog_v1.types.EntryGroup): + The entry group to create. Defaults to empty. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entry_group_id = proto.Field( + proto.STRING, + number=3, + ) + entry_group = proto.Field( + proto.MESSAGE, + number=2, + message='EntryGroup', + ) + + +class UpdateEntryGroupRequest(proto.Message): + r"""Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. + + Attributes: + entry_group (google.cloud.datacatalog_v1.types.EntryGroup): + Required. Updates for the entry group. The ``name`` field + must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on + an entry group. + If this parameter is absent or empty, all + modifiable fields are overwritten. If such + fields are non-required and omitted in the + request body, their values are emptied. + """ + + entry_group = proto.Field( + proto.MESSAGE, + number=1, + message='EntryGroup', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEntryGroupRequest(proto.Message): + r"""Request message for + [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. + + Attributes: + name (str): + Required. The name of the entry group to get. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return. If empty or omitted, + all fields are returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntryGroupRequest(proto.Message): + r"""Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. + + Attributes: + name (str): + Required. The name of the entry group to + delete. + force (bool): + Optional. If true, deletes all entries in the + entry group. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListEntryGroupsRequest(proto.Message): + r"""Request message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + + Attributes: + parent (str): + Required. The name of the location that + contains the entry groups to list. + Can be provided as a URL. + page_size (int): + Optional. The maximum number of items to return. + + Default is 10. Maximum limit is 1000. Throws an invalid + argument if ``page_size`` is greater than 1000. + page_token (str): + Optional. Pagination token that specifies the + next page to return. If empty, returns the first + page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEntryGroupsResponse(proto.Message): + r"""Response message for + [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. + + Attributes: + entry_groups (Sequence[google.cloud.datacatalog_v1.types.EntryGroup]): + Entry group details. + next_page_token (str): + Pagination token to specify in the next call + to retrieve the next page of results. Empty if + there are no more items. + """ + + @property + def raw_page(self): + return self + + entry_groups = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntryGroup', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEntryRequest(proto.Message): + r"""Request message for + [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. + + Attributes: + parent (str): + Required. The name of the entry group this + entry belongs to. + Note: The entry itself and its child resources + might not be stored in the location specified in + its name. + entry_id (str): + Required. The ID of the entry to create. + + The ID must contain only letters (a-z, A-Z), numbers (0-9), + and underscores (_). The maximum size is 64 bytes when + encoded in UTF-8. + entry (google.cloud.datacatalog_v1.types.Entry): + Required. The entry to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entry_id = proto.Field( + proto.STRING, + number=3, + ) + entry = proto.Field( + proto.MESSAGE, + number=2, + message='Entry', + ) + + +class UpdateEntryRequest(proto.Message): + r"""Request message for + [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. + + Attributes: + entry (google.cloud.datacatalog_v1.types.Entry): + Required. Updates for the entry. The ``name`` field must be + set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on an entry. + + If this parameter is absent or empty, all modifiable fields + are overwritten. If such fields are non-required and omitted + in the request body, their values are emptied. + + You can modify only the fields listed below. + + For entries with type ``DATA_STREAM``: + + - ``schema`` + + For entries with type ``FILESET``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + For entries with ``user_specified_type``: + + - ``schema`` + - ``display_name`` + - ``description`` + - ``user_specified_type`` + - ``user_specified_system`` + - ``linked_resource`` + - ``source_system_timestamps`` + """ + + entry = proto.Field( + proto.MESSAGE, + number=1, + message='Entry', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntryRequest(proto.Message): + r"""Request message for + [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. + + Attributes: + name (str): + Required. The name of the entry to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEntryRequest(proto.Message): + r"""Request message for + [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. + + Attributes: + name (str): + Required. The name of the entry to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LookupEntryRequest(proto.Message): + r"""Request message for + [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + linked_resource (str): + The full name of the Google Cloud Platform resource the Data + Catalog entry represents. For more information, see [Full + Resource Name] + (https://cloud.google.com/apis/design/resource_names#full_resource_name). + + Full names are case-sensitive. For example: + + - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` + - ``//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}`` + This field is a member of `oneof`_ ``target_name``. + sql_resource (str): + The SQL name of the entry. SQL names are case-sensitive. + + Examples: + + - ``pubsub.topic.{PROJECT_ID}.{TOPIC_ID}`` + - ``pubsub.topic.{PROJECT_ID}.``\ \`\ ``{TOPIC.ID.SEPARATED.WITH.DOTS}``\ \` + - ``bigquery.table.{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}`` + - ``bigquery.dataset.{PROJECT_ID}.{DATASET_ID}`` + - ``datacatalog.entry.{PROJECT_ID}.{LOCATION_ID}.{ENTRY_GROUP_ID}.{ENTRY_ID}`` + + Identifiers (``*_ID``) should comply with the [Lexical + structure in Standard SQL] + (https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical). + This field is a member of `oneof`_ ``target_name``. + fully_qualified_name (str): + Fully qualified name (FQN) of the resource. + + FQNs take two forms: + + - For non-regionalized resources: + + ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + - For regionalized resources: + + ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + Example for a DPMS table: + + ``dataproc_metastore:{PROJECT_ID}.{LOCATION_ID}.{INSTANCE_ID}.{DATABASE_ID}.{TABLE_ID}`` + This field is a member of `oneof`_ ``target_name``. + """ + + linked_resource = proto.Field( + proto.STRING, + number=1, + oneof='target_name', + ) + sql_resource = proto.Field( + proto.STRING, + number=3, + oneof='target_name', + ) + fully_qualified_name = proto.Field( + proto.STRING, + number=5, + oneof='target_name', + ) + + +class Entry(proto.Message): + r"""Entry metadata. A Data Catalog entry represents another resource in + Google Cloud Platform (such as a BigQuery dataset or a Pub/Sub + topic) or outside of it. You can use the ``linked_resource`` field + in the entry resource to refer to the original resource ID of the + source system. + + An entry resource contains resource details, for example, its + schema. Additionally, you can attach flexible metadata to an entry + in the form of a [Tag][google.cloud.datacatalog.v1.Tag]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The resource name of an entry in + URL format. + Note: The entry itself and its child resources + might not be stored in the location specified in + its name. + linked_resource (str): + The resource this metadata entry refers to. + + For Google Cloud Platform resources, ``linked_resource`` is + the [Full Resource Name] + (https://cloud.google.com/apis/design/resource_names#full_resource_name). + For example, the ``linked_resource`` for a table resource + from BigQuery is: + + ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` + + Output only when the entry is one of the types in the + ``EntryType`` enum. + + For entries with a ``user_specified_type``, this field is + optional and defaults to an empty string. + + The resource string must contain only letters (a-z, A-Z), + numbers (0-9), underscores (_), periods (.), colons (:), + slashes (/), dashes (-), and hashes (#). The maximum size is + 200 bytes when encoded in UTF-8. + fully_qualified_name (str): + Fully qualified name (FQN) of the resource. Set + automatically for entries representing resources from synced + systems. Settable only during creation and read-only + afterwards. Can be used for search and lookup of the + entries. + + FQNs take two forms: + + - For non-regionalized resources: + + ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + - For regionalized resources: + + ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + Example for a DPMS table: + + ``dataproc_metastore:{PROJECT_ID}.{LOCATION_ID}.{INSTANCE_ID}.{DATABASE_ID}.{TABLE_ID}`` + type_ (google.cloud.datacatalog_v1.types.EntryType): + The type of the entry. Only used for entries with types + listed in the ``EntryType`` enum. + + Currently, only ``FILESET`` enum value is allowed. All other + entries created in Data Catalog must use the + ``user_specified_type``. + This field is a member of `oneof`_ ``entry_type``. + user_specified_type (str): + Custom entry type that doesn't match any of the values + allowed for input and listed in the ``EntryType`` enum. + + When creating an entry, first check the type values in the + enum. If there are no appropriate types for the new entry, + provide a custom value, for example, ``my_special_type``. + + The ``user_specified_type`` string has the following + limitations: + + - Is case insensitive. + - Must begin with a letter or underscore. + - Can only contain letters, numbers, and underscores. + - Must be at least 1 character and at most 64 characters + long. + This field is a member of `oneof`_ ``entry_type``. + integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): + Output only. Indicates the entry's source + system that Data Catalog integrates with, such + as BigQuery, Pub/Sub, or Dataproc Metastore. + This field is a member of `oneof`_ ``system``. + user_specified_system (str): + Indicates the entry's source system that Data Catalog + doesn't automatically integrate with. + + The ``user_specified_system`` string has the following + limitations: + + - Is case insensitive. + - Must begin with a letter or underscore. + - Can only contain letters, numbers, and underscores. + - Must be at least 1 character and at most 64 characters + long. + This field is a member of `oneof`_ ``system``. + gcs_fileset_spec (google.cloud.datacatalog_v1.types.GcsFilesetSpec): + Specification that applies to a Cloud Storage fileset. Valid + only for entries with the ``FILESET`` type. + This field is a member of `oneof`_ ``type_spec``. + bigquery_table_spec (google.cloud.datacatalog_v1.types.BigQueryTableSpec): + Specification that applies to a BigQuery table. Valid only + for entries with the ``TABLE`` type. + This field is a member of `oneof`_ ``type_spec``. + bigquery_date_sharded_spec (google.cloud.datacatalog_v1.types.BigQueryDateShardedSpec): + Specification for a group of BigQuery tables with the + ``[prefix]YYYYMMDD`` name pattern. + + For more information, see [Introduction to partitioned + tables] + (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). + This field is a member of `oneof`_ ``type_spec``. + database_table_spec (google.cloud.datacatalog_v1.types.DatabaseTableSpec): + Specification that applies to a table resource. Valid only + for entries with the ``TABLE`` type. + This field is a member of `oneof`_ ``spec``. + data_source_connection_spec (google.cloud.datacatalog_v1.types.DataSourceConnectionSpec): + Specification that applies to a data source connection. + Valid only for entries with the ``DATA_SOURCE_CONNECTION`` + type. + This field is a member of `oneof`_ ``spec``. + routine_spec (google.cloud.datacatalog_v1.types.RoutineSpec): + Specification that applies to a user-defined function or + procedure. Valid only for entries with the ``ROUTINE`` type. + This field is a member of `oneof`_ ``spec``. + display_name (str): + Display name of an entry. + + The name must contain only Unicode letters, numbers (0-9), + underscores (_), dashes (-), spaces ( ), and can't start or + end with spaces. The maximum size is 200 bytes when encoded + in UTF-8. Default value is an empty string. + description (str): + Entry description that can consist of several + sentences or paragraphs that describe entry + contents. + The description must not contain Unicode non- + characters as well as C0 and C1 control codes + except tabs (HT), new lines (LF), carriage + returns (CR), and page breaks (FF). + The maximum size is 2000 bytes when encoded in + UTF-8. Default value is an empty string. + schema (google.cloud.datacatalog_v1.types.Schema): + Schema of the entry. An entry might not have + any schema attached to it. + source_system_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): + Timestamps from the underlying resource, not from the Data + Catalog entry. + + Output only when the entry has a type listed in the + ``EntryType`` enum. For entries with + ``user_specified_type``, this field is optional and defaults + to an empty timestamp. + usage_signal (google.cloud.datacatalog_v1.types.UsageSignal): + Output only. Resource usage statistics. + labels (Sequence[google.cloud.datacatalog_v1.types.Entry.LabelsEntry]): + Cloud labels attached to the entry. + In Data Catalog, you can create and modify + labels attached only to custom entries. Synced + entries have unmodifiable labels that come from + the source system. + data_source (google.cloud.datacatalog_v1.types.DataSource): + Output only. Physical location of the entry. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + linked_resource = proto.Field( + proto.STRING, + number=9, + ) + fully_qualified_name = proto.Field( + proto.STRING, + number=29, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + oneof='entry_type', + enum='EntryType', + ) + user_specified_type = proto.Field( + proto.STRING, + number=16, + oneof='entry_type', + ) + integrated_system = proto.Field( + proto.ENUM, + number=17, + oneof='system', + enum=common.IntegratedSystem, + ) + user_specified_system = proto.Field( + proto.STRING, + number=18, + oneof='system', + ) + gcs_fileset_spec = proto.Field( + proto.MESSAGE, + number=6, + oneof='type_spec', + message=gcd_gcs_fileset_spec.GcsFilesetSpec, + ) + bigquery_table_spec = proto.Field( + proto.MESSAGE, + number=12, + oneof='type_spec', + message=table_spec.BigQueryTableSpec, + ) + bigquery_date_sharded_spec = proto.Field( + proto.MESSAGE, + number=15, + oneof='type_spec', + message=table_spec.BigQueryDateShardedSpec, + ) + database_table_spec = proto.Field( + proto.MESSAGE, + number=24, + oneof='spec', + message='DatabaseTableSpec', + ) + data_source_connection_spec = proto.Field( + proto.MESSAGE, + number=27, + oneof='spec', + message='DataSourceConnectionSpec', + ) + routine_spec = proto.Field( + proto.MESSAGE, + number=28, + oneof='spec', + message='RoutineSpec', + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + schema = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_schema.Schema, + ) + source_system_timestamps = proto.Field( + proto.MESSAGE, + number=7, + message=timestamps.SystemTimestamps, + ) + usage_signal = proto.Field( + proto.MESSAGE, + number=13, + message=usage.UsageSignal, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + data_source = proto.Field( + proto.MESSAGE, + number=20, + message=gcd_data_source.DataSource, + ) + + +class DatabaseTableSpec(proto.Message): + r"""Specification that applies to a table resource. Valid only for + entries with the ``TABLE`` type. + + Attributes: + type_ (google.cloud.datacatalog_v1.types.DatabaseTableSpec.TableType): + Type of this table. + """ + class TableType(proto.Enum): + r"""Type of the table.""" + TABLE_TYPE_UNSPECIFIED = 0 + NATIVE = 1 + EXTERNAL = 2 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=TableType, + ) + + +class DataSourceConnectionSpec(proto.Message): + r"""Specification that applies to a data source connection. Valid only + for entries with the ``DATA_SOURCE_CONNECTION`` type. + + Attributes: + bigquery_connection_spec (google.cloud.datacatalog_v1.types.BigQueryConnectionSpec): + Fields specific to BigQuery connections. + """ + + bigquery_connection_spec = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery.BigQueryConnectionSpec, + ) + + +class RoutineSpec(proto.Message): + r"""Specification that applies to a routine. Valid only for entries with + the ``ROUTINE`` type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + routine_type (google.cloud.datacatalog_v1.types.RoutineSpec.RoutineType): + The type of the routine. + language (str): + The language the routine is written in. The exact value + depends on the source system. For BigQuery routines, + possible values are: + + - ``SQL`` + - ``JAVASCRIPT`` + routine_arguments (Sequence[google.cloud.datacatalog_v1.types.RoutineSpec.Argument]): + Arguments of the routine. + return_type (str): + Return type of the argument. The exact value + depends on the source system and the language. + definition_body (str): + The body of the routine. + bigquery_routine_spec (google.cloud.datacatalog_v1.types.BigQueryRoutineSpec): + Fields specific for BigQuery routines. + This field is a member of `oneof`_ ``system_spec``. + """ + class RoutineType(proto.Enum): + r"""The fine-grained type of the routine.""" + ROUTINE_TYPE_UNSPECIFIED = 0 + SCALAR_FUNCTION = 1 + PROCEDURE = 2 + + class Argument(proto.Message): + r"""Input or output argument of a function or stored procedure. + + Attributes: + name (str): + The name of the argument. A return argument + of a function might not have a name. + mode (google.cloud.datacatalog_v1.types.RoutineSpec.Argument.Mode): + Specifies whether the argument is input or + output. + type_ (str): + Type of the argument. The exact value depends + on the source system and the language. + """ + class Mode(proto.Enum): + r"""The input or output mode of the argument.""" + MODE_UNSPECIFIED = 0 + IN = 1 + OUT = 2 + INOUT = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + mode = proto.Field( + proto.ENUM, + number=2, + enum='RoutineSpec.Argument.Mode', + ) + type_ = proto.Field( + proto.STRING, + number=3, + ) + + routine_type = proto.Field( + proto.ENUM, + number=1, + enum=RoutineType, + ) + language = proto.Field( + proto.STRING, + number=2, + ) + routine_arguments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Argument, + ) + return_type = proto.Field( + proto.STRING, + number=4, + ) + definition_body = proto.Field( + proto.STRING, + number=5, + ) + bigquery_routine_spec = proto.Field( + proto.MESSAGE, + number=6, + oneof='system_spec', + message=bigquery.BigQueryRoutineSpec, + ) + + +class EntryGroup(proto.Message): + r"""Entry group metadata. + + An ``EntryGroup`` resource represents a logical grouping of zero or + more Data Catalog [Entry][google.cloud.datacatalog.v1.Entry] + resources. + + Attributes: + name (str): + The resource name of the entry group in URL + format. + Note: The entry group itself and its child + resources might not be stored in the location + specified in its name. + display_name (str): + A short name to identify the entry group, for + example, "analytics data - jan 2011". Default + value is an empty string. + description (str): + Entry group description. Can consist of + several sentences or paragraphs that describe + the entry group contents. Default value is an + empty string. + data_catalog_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): + Output only. Timestamps of the entry group. + Default value is empty. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + data_catalog_timestamps = proto.Field( + proto.MESSAGE, + number=4, + message=timestamps.SystemTimestamps, + ) + + +class CreateTagTemplateRequest(proto.Message): + r"""Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. + + Attributes: + parent (str): + Required. The name of the project and the template location + `region `__. + tag_template_id (str): + Required. The ID of the tag template to create. + + The ID must contain only lowercase letters (a-z), numbers + (0-9), or underscores (_), and must start with a letter or + underscore. The maximum size is 64 bytes when encoded in + UTF-8. + tag_template (google.cloud.datacatalog_v1.types.TagTemplate): + Required. The tag template to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag_template_id = proto.Field( + proto.STRING, + number=3, + ) + tag_template = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.TagTemplate, + ) + + +class GetTagTemplateRequest(proto.Message): + r"""Request message for + [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. + + Attributes: + name (str): + Required. The name of the tag template to + get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTagTemplateRequest(proto.Message): + r"""Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. + + Attributes: + tag_template (google.cloud.datacatalog_v1.types.TagTemplate): + Required. The template to update. The ``name`` field must be + set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on a tag template. + Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. + + If this parameter is absent or empty, all modifiable fields + are overwritten. If such fields are non-required and omitted + in the request body, their values are emptied. + + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. + """ + + tag_template = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_tags.TagTemplate, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteTagTemplateRequest(proto.Message): + r"""Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. + + Attributes: + name (str): + Required. The name of the tag template to + delete. + force (bool): + Required. If true, deletes all tags that use this template. + + Currently, ``true`` is the only supported value. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class CreateTagRequest(proto.Message): + r"""Request message for + [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. + + Attributes: + parent (str): + Required. The name of the resource to attach + this tag to. + Tags can be attached to entries or entry groups. + An entry can have up to 1000 attached tags. + + Note: The tag and its child resources might not + be stored in the location specified in its name. + tag (google.cloud.datacatalog_v1.types.Tag): + Required. The tag to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.Tag, + ) + + +class UpdateTagRequest(proto.Message): + r"""Request message for + [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. + + Attributes: + tag (google.cloud.datacatalog_v1.types.Tag): + Required. The updated tag. The "name" field + must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Names of fields whose values to overwrite on a tag. + Currently, a tag has the only modifiable field with the name + ``fields``. + + In general, if this parameter is absent or empty, all + modifiable fields are overwritten. If such fields are + non-required and omitted in the request body, their values + are emptied. + """ + + tag = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_tags.Tag, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteTagRequest(proto.Message): + r"""Request message for + [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. + + Attributes: + name (str): + Required. The name of the tag to delete. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTagTemplateFieldRequest(proto.Message): + r"""Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. + + Attributes: + parent (str): + Required. The name of the project and the template location + `region `__. + tag_template_field_id (str): + Required. The ID of the tag template field to create. + + Note: Adding a required field to an existing template is + *not* allowed. + + Field IDs can contain letters (both uppercase and + lowercase), numbers (0-9), underscores (_) and dashes (-). + Field IDs must be at least 1 character long and at most 128 + characters long. Field IDs must also be unique within their + template. + tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): + Required. The tag template field to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag_template_field_id = proto.Field( + proto.STRING, + number=2, + ) + tag_template_field = proto.Field( + proto.MESSAGE, + number=3, + message=gcd_tags.TagTemplateField, + ) + + +class UpdateTagTemplateFieldRequest(proto.Message): + r"""Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template field. + tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): + Required. The template to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Names of fields whose values to overwrite on an + individual field of a tag template. The following fields are + modifiable: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If this parameter is absent or empty, all modifiable fields + are overwritten. If such fields are non-required and omitted + in the request body, their values are emptied with one + exception: when updating an enum type, the provided values + are merged with the existing values. Therefore, enum values + can only be added, existing enum values cannot be deleted or + renamed. + + Additionally, updating a template field from optional to + required is *not* allowed. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + tag_template_field = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.TagTemplateField, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class RenameTagTemplateFieldRequest(proto.Message): + r"""Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template field. + new_tag_template_field_id (str): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + new_tag_template_field_id = proto.Field( + proto.STRING, + number=2, + ) + + +class RenameTagTemplateFieldEnumValueRequest(proto.Message): + r"""Request message for + [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. + + Attributes: + name (str): + Required. The name of the enum field value. + new_enum_value_display_name (str): + Required. The new display name of the enum value. For + example, ``my_new_enum_value``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + new_enum_value_display_name = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteTagTemplateFieldRequest(proto.Message): + r"""Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template field + to delete. + force (bool): + Required. If true, deletes this field from any tags that use + it. + + Currently, ``true`` is the only supported value. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListTagsRequest(proto.Message): + r"""Request message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + + Attributes: + parent (str): + Required. The name of the Data Catalog resource to list the + tags of. + + The resource can be an + [Entry][google.cloud.datacatalog.v1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] + (without ``/entries/{entries}`` at the end). + page_size (int): + The maximum number of tags to return. Default + is 10. Maximum limit is 1000. + page_token (str): + Pagination token that specifies the next page + to return. If empty, the first page is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTagsResponse(proto.Message): + r"""Response message for + [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. + + Attributes: + tags (Sequence[google.cloud.datacatalog_v1.types.Tag]): + [Tag][google.cloud.datacatalog.v1.Tag] details. + next_page_token (str): + Pagination token of the next results page. + Empty if there are no more items in results. + """ + + @property + def raw_page(self): + return self + + tags = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_tags.Tag, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEntriesRequest(proto.Message): + r"""Request message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + + Attributes: + parent (str): + Required. The name of the entry group that + contains the entries to list. + Can be provided in URL format. + page_size (int): + The maximum number of items to return. Default is 10. + Maximum limit is 1000. Throws an invalid argument if + ``page_size`` is more than 1000. + page_token (str): + Pagination token that specifies the next page + to return. If empty, the first page is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return for each entry. If empty or omitted, + all fields are returned. + + For example, to return a list of entries with only the + ``name`` field, set ``read_mask`` to only one path with the + ``name`` value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class ListEntriesResponse(proto.Message): + r"""Response message for + [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. + + Attributes: + entries (Sequence[google.cloud.datacatalog_v1.types.Entry]): + Entry details. + next_page_token (str): + Pagination token of the next results page. + Empty if there are no more items in results. + """ + + @property + def raw_page(self): + return self + + entries = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Entry', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py new file mode 100644 index 00000000..6d1800ee --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py @@ -0,0 +1,115 @@ +# -*- 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.datacatalog_v1.types import timestamps + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'GcsFilesetSpec', + 'GcsFileSpec', + }, +) + + +class GcsFilesetSpec(proto.Message): + r"""Describes a Cloud Storage fileset entry. + + Attributes: + file_patterns (Sequence[str]): + Required. Patterns to identify a set of files in Google + Cloud Storage. + + For more information, see [Wildcard Names] + (https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames). + + Note: Currently, bucket wildcards are not supported. + + Examples of valid ``file_patterns``: + + - ``gs://bucket_name/dir/*``: matches all files in + ``bucket_name/dir`` directory + - ``gs://bucket_name/dir/**``: matches all files in + ``bucket_name/dir`` and all subdirectories + - ``gs://bucket_name/file*``: matches files prefixed by + ``file`` in ``bucket_name`` + - ``gs://bucket_name/??.txt``: matches files with two + characters followed by ``.txt`` in ``bucket_name`` + - ``gs://bucket_name/[aeiou].txt``: matches files that + contain a single vowel character followed by ``.txt`` in + ``bucket_name`` + - ``gs://bucket_name/[a-m].txt``: matches files that + contain ``a``, ``b``, ... or ``m`` followed by ``.txt`` + in ``bucket_name`` + - ``gs://bucket_name/a/*/b``: matches all files in + ``bucket_name`` that match the ``a/*/b`` pattern, such as + ``a/c/b``, ``a/d/b`` + - ``gs://another_bucket/a.txt``: matches + ``gs://another_bucket/a.txt`` + + You can combine wildcards to match complex sets of files, + for example: + + ``gs://bucket_name/[a-m]??.j*g`` + sample_gcs_file_specs (Sequence[google.cloud.datacatalog_v1.types.GcsFileSpec]): + Output only. Sample files contained in this + fileset, not all files contained in this fileset + are represented here. + """ + + file_patterns = proto.RepeatedField( + proto.STRING, + number=1, + ) + sample_gcs_file_specs = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='GcsFileSpec', + ) + + +class GcsFileSpec(proto.Message): + r"""Specification of a single file in Cloud Storage. + + Attributes: + file_path (str): + Required. Full file path. Example: + ``gs://bucket_name/a/b.txt``. + gcs_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): + Output only. Creation, modification, and + expiration timestamps of a Cloud Storage file. + size_bytes (int): + Output only. File size in bytes. + """ + + file_path = proto.Field( + proto.STRING, + number=1, + ) + gcs_timestamps = proto.Field( + proto.MESSAGE, + number=2, + message=timestamps.SystemTimestamps, + ) + size_bytes = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py new file mode 100644 index 00000000..e212b29e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py @@ -0,0 +1,495 @@ +# -*- 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.datacatalog_v1.types import timestamps +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'Taxonomy', + 'PolicyTag', + 'CreateTaxonomyRequest', + 'DeleteTaxonomyRequest', + 'UpdateTaxonomyRequest', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'GetTaxonomyRequest', + 'CreatePolicyTagRequest', + 'DeletePolicyTagRequest', + 'UpdatePolicyTagRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'GetPolicyTagRequest', + }, +) + + +class Taxonomy(proto.Message): + r"""A taxonomy is a collection of hierarchical policy tags that classify + data along a common axis. + + For example, a "data sensitivity" taxonomy might contain the + following policy tags: + + :: + + + PII + + Account number + + Age + + SSN + + Zipcode + + Financials + + Revenue + + A "data origin" taxonomy might contain the following policy tags: + + :: + + + User data + + Employee data + + Partner data + + Public data + + Attributes: + name (str): + Output only. Resource name of this taxonomy + in URL format. + Note: Policy tag manager generates unique + taxonomy IDs. + display_name (str): + Required. User-defined name of this taxonomy. + The name can't start or end with spaces, must + contain only Unicode letters, numbers, + underscores, dashes, and spaces, and be at most + 200 bytes long when encoded in UTF-8. + description (str): + Optional. Description of this taxonomy. If + not set, defaults to empty. + The description must contain only Unicode + characters, tabs, newlines, carriage returns, + and page breaks, and be at most 2000 bytes long + when encoded in UTF-8. + policy_tag_count (int): + Output only. Number of policy tags in this + taxonomy. + taxonomy_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): + Output only. Creation and modification + timestamps of this taxonomy. + activated_policy_types (Sequence[google.cloud.datacatalog_v1.types.Taxonomy.PolicyType]): + Optional. A list of policy types that are + activated for this taxonomy. If not set, + defaults to an empty list. + """ + class PolicyType(proto.Enum): + r"""Defines policy types where the policy tags can be used for.""" + POLICY_TYPE_UNSPECIFIED = 0 + FINE_GRAINED_ACCESS_CONTROL = 1 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + policy_tag_count = proto.Field( + proto.INT32, + number=4, + ) + taxonomy_timestamps = proto.Field( + proto.MESSAGE, + number=5, + message=timestamps.SystemTimestamps, + ) + activated_policy_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=PolicyType, + ) + + +class PolicyTag(proto.Message): + r"""Denotes one policy tag in a taxonomy, for example, SSN. + + Policy tags can be defined in a hierarchy. For example: + + :: + + + Geolocation + + LatLong + + City + + ZipCode + + Where the "Geolocation" policy tag contains three children. + + Attributes: + name (str): + Output only. Resource name of this policy tag + in the URL format. + The policy tag manager generates unique taxonomy + IDs and policy tag IDs. + display_name (str): + Required. User-defined name of this policy + tag. + The name can't start or end with spaces and must + be unique within the parent taxonomy, contain + only Unicode letters, numbers, underscores, + dashes and spaces, and be at most 200 bytes long + when encoded in UTF-8. + description (str): + Description of this policy tag. If not set, + defaults to empty. + The description must contain only Unicode + characters, tabs, newlines, carriage returns and + page breaks, and be at most 2000 bytes long when + encoded in UTF-8. + parent_policy_tag (str): + Resource name of this policy tag's parent + policy tag. If empty, this is a top level tag. + If not set, defaults to an empty string. + For example, for the "LatLong" policy tag in the + example above, this field contains the resource + name of the "Geolocation" policy tag, and, for + "Geolocation", this field is empty. + child_policy_tags (Sequence[str]): + Output only. Resource names of child policy + tags of this policy tag. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + parent_policy_tag = proto.Field( + proto.STRING, + number=4, + ) + child_policy_tags = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class CreateTaxonomyRequest(proto.Message): + r"""Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. + + Attributes: + parent (str): + Required. Resource name of the project that + the taxonomy will belong to. + taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): + The taxonomy to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + taxonomy = proto.Field( + proto.MESSAGE, + number=2, + message='Taxonomy', + ) + + +class DeleteTaxonomyRequest(proto.Message): + r"""Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. + + Attributes: + name (str): + Required. Resource name of the taxonomy to + delete. + Note: All policy tags in this taxonomy are also + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTaxonomyRequest(proto.Message): + r"""Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. + + Attributes: + taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): + The taxonomy to update. You can update only + its description, display name, and activated + policy types. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Specifies fields to update. If not set, defaults to all + fields you can update. + + For more information, see [FieldMask] + (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask). + """ + + taxonomy = proto.Field( + proto.MESSAGE, + number=1, + message='Taxonomy', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListTaxonomiesRequest(proto.Message): + r"""Request message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + + Attributes: + parent (str): + Required. Resource name of the project to + list the taxonomies of. + page_size (int): + The maximum number of items to return. Must + be a value between 1 and 1000 inclusively. If + not set, defaults to 50. + page_token (str): + The pagination token of the next results + page. If not set, the first page is returned. + The token is returned in the response to a + previous list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTaxonomiesResponse(proto.Message): + r"""Response message for + [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1.types.Taxonomy]): + Taxonomies that the project contains. + next_page_token (str): + Pagination token of the next results page. + Empty if there are no more results in the list. + """ + + @property + def raw_page(self): + return self + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Taxonomy', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTaxonomyRequest(proto.Message): + r"""Request message for + [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. + + Attributes: + name (str): + Required. Resource name of the taxonomy to + get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePolicyTagRequest(proto.Message): + r"""Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. + + Attributes: + parent (str): + Required. Resource name of the taxonomy that + the policy tag will belong to. + policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): + The policy tag to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + policy_tag = proto.Field( + proto.MESSAGE, + number=2, + message='PolicyTag', + ) + + +class DeletePolicyTagRequest(proto.Message): + r"""Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. + + Attributes: + name (str): + Required. Resource name of the policy tag to + delete. + Note: All of its descendant policy tags are also + deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePolicyTagRequest(proto.Message): + r"""Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. + + Attributes: + policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): + The policy tag to update. You can update only + its description, display name, and parent policy + tag fields. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Specifies the fields to update. + + You can update only display name, description, and parent + policy tag. If not set, defaults to all updatable fields. + For more information, see [FieldMask] + (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask). + """ + + policy_tag = proto.Field( + proto.MESSAGE, + number=1, + message='PolicyTag', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListPolicyTagsRequest(proto.Message): + r"""Request message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + + Attributes: + parent (str): + Required. Resource name of the taxonomy to + list the policy tags of. + page_size (int): + The maximum number of items to return. Must + be a value between 1 and 1000 inclusively. + If not set, defaults to 50. + page_token (str): + The pagination token of the next results + page. If not set, returns the first page. + + The token is returned in the response to a + previous list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPolicyTagsResponse(proto.Message): + r"""Response message for + [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. + + Attributes: + policy_tags (Sequence[google.cloud.datacatalog_v1.types.PolicyTag]): + The policy tags that belong to the taxonomy. + next_page_token (str): + Pagination token of the next results page. + Empty if there are no more results in the list. + """ + + @property + def raw_page(self): + return self + + policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PolicyTag', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPolicyTagRequest(proto.Message): + r"""Request message for + [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. + + Attributes: + name (str): + Required. Resource name of the policy tag. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py new file mode 100644 index 00000000..9b195aa3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py @@ -0,0 +1,281 @@ +# -*- 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.datacatalog_v1.types import policytagmanager + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'SerializedTaxonomy', + 'SerializedPolicyTag', + 'ReplaceTaxonomyRequest', + 'ImportTaxonomiesRequest', + 'InlineSource', + 'CrossRegionalSource', + 'ImportTaxonomiesResponse', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + }, +) + + +class SerializedTaxonomy(proto.Message): + r"""A nested protocol buffer that represents a taxonomy and the + hierarchy of its policy tags. Used for taxonomy replacement, + import, and export. + + Attributes: + display_name (str): + Required. Display name of the taxonomy. At + most 200 bytes when encoded in UTF-8. + description (str): + Description of the serialized taxonomy. At + most 2000 bytes when encoded in UTF-8. If not + set, defaults to an empty description. + policy_tags (Sequence[google.cloud.datacatalog_v1.types.SerializedPolicyTag]): + Top level policy tags associated with the + taxonomy, if any. + activated_policy_types (Sequence[google.cloud.datacatalog_v1.types.Taxonomy.PolicyType]): + A list of policy types that are activated per + taxonomy. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='SerializedPolicyTag', + ) + activated_policy_types = proto.RepeatedField( + proto.ENUM, + number=4, + enum=policytagmanager.Taxonomy.PolicyType, + ) + + +class SerializedPolicyTag(proto.Message): + r"""A nested protocol buffer that represents a policy tag and all + its descendants. + + Attributes: + policy_tag (str): + Resource name of the policy tag. + + This field is ignored when calling ``ImportTaxonomies``. + display_name (str): + Required. Display name of the policy tag. At + most 200 bytes when encoded in UTF-8. + description (str): + Description of the serialized policy tag. At + most 2000 bytes when encoded in UTF-8. If not + set, defaults to an empty description. + child_policy_tags (Sequence[google.cloud.datacatalog_v1.types.SerializedPolicyTag]): + Children of the policy tag, if any. + """ + + policy_tag = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + child_policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SerializedPolicyTag', + ) + + +class ReplaceTaxonomyRequest(proto.Message): + r"""Request message for + [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. + + Attributes: + name (str): + Required. Resource name of the taxonomy to + update. + serialized_taxonomy (google.cloud.datacatalog_v1.types.SerializedTaxonomy): + Required. Taxonomy to update along with its + child policy tags. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + serialized_taxonomy = proto.Field( + proto.MESSAGE, + number=2, + message='SerializedTaxonomy', + ) + + +class ImportTaxonomiesRequest(proto.Message): + r"""Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Resource name of project that the + imported taxonomies will belong to. + inline_source (google.cloud.datacatalog_v1.types.InlineSource): + Inline source taxonomy to import. + This field is a member of `oneof`_ ``source``. + cross_regional_source (google.cloud.datacatalog_v1.types.CrossRegionalSource): + Cross-regional source taxonomy to import. + This field is a member of `oneof`_ ``source``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + inline_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='InlineSource', + ) + cross_regional_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='CrossRegionalSource', + ) + + +class InlineSource(proto.Message): + r"""Inline source containing taxonomies to import. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1.types.SerializedTaxonomy]): + Required. Taxonomies to import. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SerializedTaxonomy', + ) + + +class CrossRegionalSource(proto.Message): + r"""Cross-regional source used to import an existing taxonomy + into a different region. + + Attributes: + taxonomy (str): + Required. The resource name of the source + taxonomy to import. + """ + + taxonomy = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportTaxonomiesResponse(proto.Message): + r"""Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1.types.Taxonomy]): + Imported taxonomies. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policytagmanager.Taxonomy, + ) + + +class ExportTaxonomiesRequest(proto.Message): + r"""Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Resource name of the project that + the exported taxonomies belong to. + taxonomies (Sequence[str]): + Required. Resource names of the taxonomies to + export. + serialized_taxonomies (bool): + Serialized export taxonomies that contain all + the policy tags as nested protocol buffers. + This field is a member of `oneof`_ ``destination``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + taxonomies = proto.RepeatedField( + proto.STRING, + number=2, + ) + serialized_taxonomies = proto.Field( + proto.BOOL, + number=3, + oneof='destination', + ) + + +class ExportTaxonomiesResponse(proto.Message): + r"""Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1.types.SerializedTaxonomy]): + List of taxonomies and policy tags as nested + protocol buffers. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SerializedTaxonomy', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py new file mode 100644 index 00000000..048a165a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py @@ -0,0 +1,99 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'Schema', + 'ColumnSchema', + }, +) + + +class Schema(proto.Message): + r"""Represents a schema, for example, a BigQuery, GoogleSQL, or + Avro schema. + + Attributes: + columns (Sequence[google.cloud.datacatalog_v1.types.ColumnSchema]): + The unified GoogleSQL-like schema of columns. + The overall maximum number of columns and nested + columns is 10,000. The maximum nested depth is + 15 levels. + """ + + columns = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ColumnSchema', + ) + + +class ColumnSchema(proto.Message): + r"""A column within a schema. Columns can be nested inside + other columns. + + Attributes: + column (str): + Required. Name of the column. + Must be a UTF-8 string without dots (.). + The maximum size is 64 bytes. + type_ (str): + Required. Type of the column. + Must be a UTF-8 string with the maximum size of + 128 bytes. + description (str): + Optional. Description of the column. Default + value is an empty string. + The description must be a UTF-8 string with the + maximum size of 2000 bytes. + mode (str): + Optional. A column's mode indicates whether values in this + column are required, nullable, or repeated. + + Only ``NULLABLE``, ``REQUIRED``, and ``REPEATED`` values are + supported. Default mode is ``NULLABLE``. + subcolumns (Sequence[google.cloud.datacatalog_v1.types.ColumnSchema]): + Optional. Schema of sub-columns. A column can + have zero or more sub-columns. + """ + + column = proto.Field( + proto.STRING, + number=6, + ) + type_ = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + mode = proto.Field( + proto.STRING, + number=3, + ) + subcolumns = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ColumnSchema', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py new file mode 100644 index 00000000..bce6e920 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py @@ -0,0 +1,164 @@ +# -*- 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.datacatalog_v1.types import common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'SearchResultType', + 'SearchCatalogResult', + }, +) + + +class SearchResultType(proto.Enum): + r"""The resource types that can be returned in search results.""" + SEARCH_RESULT_TYPE_UNSPECIFIED = 0 + ENTRY = 1 + TAG_TEMPLATE = 2 + ENTRY_GROUP = 3 + + +class SearchCatalogResult(proto.Message): + r"""Result in the response to a search request. + Each result captures details of one entry that matches the + search. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_result_type (google.cloud.datacatalog_v1.types.SearchResultType): + Type of the search result. + You can use this field to determine which get + method to call to fetch the full resource. + search_result_subtype (str): + Sub-type of the search result. + + A dot-delimited full type of the resource. The same type you + specify in the ``type`` search predicate. + + Examples: ``entry.table``, ``entry.dataStream``, + ``tagTemplate``. + relative_resource_name (str): + The relative name of the resource in URL format. + + Examples: + + - ``projects/{PROJECT_ID}/locations/{LOCATION_ID}/entryGroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}`` + - ``projects/{PROJECT_ID}/tagTemplates/{TAG_TEMPLATE_ID}`` + linked_resource (str): + The full name of the Google Cloud resource the entry belongs + to. + + For more information, see [Full Resource Name] + (/apis/design/resource_names#full_resource_name). + + Example: + + ``//bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID`` + modify_time (google.protobuf.timestamp_pb2.Timestamp): + The last modification timestamp of the entry + in the source system. + integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): + Output only. The source system that Data + Catalog automatically integrates with, such as + BigQuery, Cloud Pub/Sub, or Dataproc Metastore. + This field is a member of `oneof`_ ``system``. + user_specified_system (str): + Custom source system that you can manually + integrate Data Catalog with. + This field is a member of `oneof`_ ``system``. + fully_qualified_name (str): + Fully qualified name (FQN) of the resource. + + FQNs take two forms: + + - For non-regionalized resources: + + ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + - For regionalized resources: + + ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` + + Example for a DPMS table: + + ``dataproc_metastore:PROJECT_ID.LOCATION_ID.INSTANCE_ID.DATABASE_ID.TABLE_ID`` + display_name (str): + The display name of the result. + description (str): + Entry description that can consist of several + sentences or paragraphs that describe entry + contents. + """ + + search_result_type = proto.Field( + proto.ENUM, + number=1, + enum='SearchResultType', + ) + search_result_subtype = proto.Field( + proto.STRING, + number=2, + ) + relative_resource_name = proto.Field( + proto.STRING, + number=3, + ) + linked_resource = proto.Field( + proto.STRING, + number=4, + ) + modify_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + integrated_system = proto.Field( + proto.ENUM, + number=8, + oneof='system', + enum=common.IntegratedSystem, + ) + user_specified_system = proto.Field( + proto.STRING, + number=9, + oneof='system', + ) + fully_qualified_name = proto.Field( + proto.STRING, + number=10, + ) + display_name = proto.Field( + proto.STRING, + number=12, + ) + description = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py new file mode 100644 index 00000000..e457cf11 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py @@ -0,0 +1,161 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'TableSourceType', + 'BigQueryTableSpec', + 'ViewSpec', + 'TableSpec', + 'BigQueryDateShardedSpec', + }, +) + + +class TableSourceType(proto.Enum): + r"""Table source type.""" + TABLE_SOURCE_TYPE_UNSPECIFIED = 0 + BIGQUERY_VIEW = 2 + BIGQUERY_TABLE = 5 + BIGQUERY_MATERIALIZED_VIEW = 7 + + +class BigQueryTableSpec(proto.Message): + r"""Describes a BigQuery table. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + table_source_type (google.cloud.datacatalog_v1.types.TableSourceType): + Output only. The table source type. + view_spec (google.cloud.datacatalog_v1.types.ViewSpec): + Table view specification. Populated only if the + ``table_source_type`` is ``BIGQUERY_VIEW``. + This field is a member of `oneof`_ ``type_spec``. + table_spec (google.cloud.datacatalog_v1.types.TableSpec): + Specification of a BigQuery table. Populated only if the + ``table_source_type`` is ``BIGQUERY_TABLE``. + This field is a member of `oneof`_ ``type_spec``. + """ + + table_source_type = proto.Field( + proto.ENUM, + number=1, + enum='TableSourceType', + ) + view_spec = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_spec', + message='ViewSpec', + ) + table_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='type_spec', + message='TableSpec', + ) + + +class ViewSpec(proto.Message): + r"""Table view specification. + + Attributes: + view_query (str): + Output only. The query that defines the table + view. + """ + + view_query = proto.Field( + proto.STRING, + number=1, + ) + + +class TableSpec(proto.Message): + r"""Normal BigQuery table specification. + + Attributes: + grouped_entry (str): + Output only. If the table is date-sharded, that is, it + matches the ``[prefix]YYYYMMDD`` name pattern, this field is + the Data Catalog resource name of the date-sharded grouped + entry. For example: + + ``projects/{PROJECT_ID}/locations/{LOCATION}/entrygroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}``. + + Otherwise, ``grouped_entry`` is empty. + """ + + grouped_entry = proto.Field( + proto.STRING, + number=1, + ) + + +class BigQueryDateShardedSpec(proto.Message): + r"""Specification for a group of BigQuery tables with the + ``[prefix]YYYYMMDD`` name pattern. + + For more information, see [Introduction to partitioned tables] + (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). + + Attributes: + dataset (str): + Output only. The Data Catalog resource name of the dataset + entry the current table belongs to. For example: + + ``projects/{PROJECT_ID}/locations/{LOCATION}/entrygroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}``. + table_prefix (str): + Output only. The table name prefix of the shards. + + The name of any given shard is ``[table_prefix]YYYYMMDD``. + For example, for the ``MyTable20180101`` shard, the + ``table_prefix`` is ``MyTable``. + shard_count (int): + Output only. Total number of shards. + latest_shard_resource (str): + Output only. BigQuery resource name of the + latest shard. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + table_prefix = proto.Field( + proto.STRING, + number=2, + ) + shard_count = proto.Field( + proto.INT64, + number=3, + ) + latest_shard_resource = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py new file mode 100644 index 00000000..6a6a8a8d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py @@ -0,0 +1,458 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'FieldType', + }, +) + + +class Tag(proto.Message): + r"""Tags contain custom metadata and are attached to Data Catalog + resources. Tags conform with the specification of their tag + template. + + See `Data Catalog + IAM `__ for + information on the permissions needed to create or view tags. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the tag in URL format + where tag ID is a system-generated identifier. + Note: The tag itself might not be stored in the + location specified in its name. + template (str): + Required. The resource name of the tag template this tag + uses. Example: + + ``projects/{PROJECT_ID}/locations/{LOCATION}/tagTemplates/{TAG_TEMPLATE_ID}`` + + This field cannot be modified after creation. + template_display_name (str): + Output only. The display name of the tag + template. + column (str): + Resources like entry can have schemas associated with them. + This scope allows you to attach tags to an individual column + based on that schema. + + To attach a tag to a nested column, separate column names + with a dot (``.``). Example: ``column.nested_column``. + This field is a member of `oneof`_ ``scope``. + fields (Sequence[google.cloud.datacatalog_v1.types.Tag.FieldsEntry]): + Required. Maps the ID of a tag field to its + value and additional information about that + field. + Tag template defines valid field IDs. A tag + must have at least 1 field and at most 500 + fields. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + template = proto.Field( + proto.STRING, + number=2, + ) + template_display_name = proto.Field( + proto.STRING, + number=5, + ) + column = proto.Field( + proto.STRING, + number=4, + oneof='scope', + ) + fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='TagField', + ) + + +class TagField(proto.Message): + r"""Contains the value and additional information on a field within a + [Tag][google.cloud.datacatalog.v1.Tag]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + Output only. The display name of this field. + double_value (float): + The value of a tag field with a double type. + This field is a member of `oneof`_ ``kind``. + string_value (str): + The value of a tag field with a string type. + The maximum length is 2000 UTF-8 characters. + This field is a member of `oneof`_ ``kind``. + bool_value (bool): + The value of a tag field with a boolean type. + This field is a member of `oneof`_ ``kind``. + timestamp_value (google.protobuf.timestamp_pb2.Timestamp): + The value of a tag field with a timestamp + type. + This field is a member of `oneof`_ ``kind``. + enum_value (google.cloud.datacatalog_v1.types.TagField.EnumValue): + The value of a tag field with an enum type. + This value must be one of the allowed values + listed in this enum. + This field is a member of `oneof`_ ``kind``. + richtext_value (str): + The value of a tag field with a rich text + type. + The maximum length is 10 MiB as this value holds + HTML descriptions including encoded images. The + maximum length of the text without images is 100 + KiB. + This field is a member of `oneof`_ ``kind``. + order (int): + Output only. The order of this field with respect to other + fields in this tag. Can be set by + [Tag][google.cloud.datacatalog.v1.TagTemplateField.order]. + + For example, a higher value can indicate a more important + field. The value can be negative. Multiple fields can have + the same order, and field orders within a tag don't have to + be sequential. + """ + + class EnumValue(proto.Message): + r"""An enum value. + + Attributes: + display_name (str): + The display name of the enum value. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + double_value = proto.Field( + proto.DOUBLE, + number=2, + oneof='kind', + ) + string_value = proto.Field( + proto.STRING, + number=3, + oneof='kind', + ) + bool_value = proto.Field( + proto.BOOL, + number=4, + oneof='kind', + ) + timestamp_value = proto.Field( + proto.MESSAGE, + number=5, + oneof='kind', + message=timestamp_pb2.Timestamp, + ) + enum_value = proto.Field( + proto.MESSAGE, + number=6, + oneof='kind', + message=EnumValue, + ) + richtext_value = proto.Field( + proto.STRING, + number=8, + oneof='kind', + ) + order = proto.Field( + proto.INT32, + number=7, + ) + + +class TagTemplate(proto.Message): + r"""A tag template defines a tag that can have one or more typed fields. + + The template is used to create tags that are attached to GCP + resources. [Tag template roles] + (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the template. For + example, see the [TagTemplate User] + (https://cloud.google.com/data-catalog/docs/how-to/template-user) + role that includes a permission to use the tag template to tag + resources. + + Attributes: + name (str): + The resource name of the tag template in URL + format. + Note: The tag template itself and its child + resources might not be stored in the location + specified in its name. + display_name (str): + Display name for this template. Defaults to an empty string. + + The name must contain only Unicode letters, numbers (0-9), + underscores (_), dashes (-), spaces ( ), and can't start or + end with spaces. The maximum length is 200 characters. + is_publicly_readable (bool): + Indicates whether this is a public tag template. + + Every user has view access to a *public* tag template by + default. This means that: + + - Every user can use this tag template to tag an entry. + - If an entry is tagged using the tag template, the tag is + always shown in the response to ``ListTags`` called on + the entry. + - To get the template using the GetTagTemplate method, you + need view access either on the project or the + organization the tag template resides in but no other + permission is needed. + - Operations on the tag template other than viewing (for + example, editing IAM policies) follow standard IAM + structures. + + Tags created with a public tag template are referred to as + public tags. + + You can search for a public tag by value with a simple + search query instead of using a ``tag:`` predicate. + + Public tag templates may not appear in search results + depending on scope, see: + [include_public_tag_templates][google.cloud.datacatalog.v1.SearchCatalogRequest.Scope.include_public_tag_templates] + + Note: If an `IAM domain + restriction `__ + is configured in the tag template's location, the public + access will not be enabled but the simple search for tag + values will still work. + fields (Sequence[google.cloud.datacatalog_v1.types.TagTemplate.FieldsEntry]): + Required. Map of tag template field IDs to the settings for + the field. This map is an exhaustive list of the allowed + fields. The map must contain at least one field and at most + 500 fields. + + The keys to this map are tag template field IDs. The IDs + have the following limitations: + + - Can contain uppercase and lowercase letters, numbers + (0-9) and underscores (_). + - Must be at least 1 character and at most 64 characters + long. + - Must start with a letter or underscore. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + is_publicly_readable = proto.Field( + proto.BOOL, + number=5, + ) + fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='TagTemplateField', + ) + + +class TagTemplateField(proto.Message): + r"""The template for an individual field within a tag template. + + Attributes: + name (str): + Output only. The resource name of the tag template field in + URL format. Example: + + ``projects/{PROJECT_ID}/locations/{LOCATION}/tagTemplates/{TAG_TEMPLATE}/fields/{FIELD}`` + + Note: The tag template field itself might not be stored in + the location specified in its name. + + The name must contain only letters (a-z, A-Z), numbers + (0-9), or underscores (_), and must start with a letter or + underscore. The maximum length is 64 characters. + display_name (str): + The display name for this field. Defaults to an empty + string. + + The name must contain only Unicode letters, numbers (0-9), + underscores (_), dashes (-), spaces ( ), and can't start or + end with spaces. The maximum length is 200 characters. + type_ (google.cloud.datacatalog_v1.types.FieldType): + Required. The type of value this tag field + can contain. + is_required (bool): + If true, this field is required. Defaults to + false. + description (str): + The description for this field. Defaults to + an empty string. + order (int): + The order of this field with respect to other + fields in this tag template. + + For example, a higher value can indicate a more + important field. The value can be negative. + Multiple fields can have the same order and + field orders within a tag don't have to be + sequential. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + display_name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.MESSAGE, + number=2, + message='FieldType', + ) + is_required = proto.Field( + proto.BOOL, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + order = proto.Field( + proto.INT32, + number=5, + ) + + +class FieldType(proto.Message): + r""" + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + primitive_type (google.cloud.datacatalog_v1.types.FieldType.PrimitiveType): + Primitive types, such as string, boolean, + etc. + This field is a member of `oneof`_ ``type_decl``. + enum_type (google.cloud.datacatalog_v1.types.FieldType.EnumType): + An enum type. + This field is a member of `oneof`_ ``type_decl``. + """ + class PrimitiveType(proto.Enum): + r"""""" + PRIMITIVE_TYPE_UNSPECIFIED = 0 + DOUBLE = 1 + STRING = 2 + BOOL = 3 + TIMESTAMP = 4 + RICHTEXT = 5 + + class EnumType(proto.Message): + r""" + + Attributes: + allowed_values (Sequence[google.cloud.datacatalog_v1.types.FieldType.EnumType.EnumValue]): + The set of allowed values for this enum. + + This set must not be empty and can include up to 100 allowed + values. The display names of the values in this set must not + be empty and must be case-insensitively unique within this + set. + + The order of items in this set is preserved. This field can + be used to create, remove, and reorder enum values. To + rename enum values, use the + ``RenameTagTemplateFieldEnumValue`` method. + """ + + class EnumValue(proto.Message): + r""" + + Attributes: + display_name (str): + Required. The display name of the enum value. Must not be an + empty string. + + The name must contain only Unicode letters, numbers (0-9), + underscores (_), dashes (-), spaces ( ), and can't start or + end with spaces. The maximum length is 200 characters. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + + allowed_values = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FieldType.EnumType.EnumValue', + ) + + primitive_type = proto.Field( + proto.ENUM, + number=1, + oneof='type_decl', + enum=PrimitiveType, + ) + enum_type = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_decl', + message=EnumType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py new file mode 100644 index 00000000..fbda615c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py @@ -0,0 +1,67 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'SystemTimestamps', + }, +) + + +class SystemTimestamps(proto.Message): + r"""Timestamps associated with this resource in a particular + system. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation timestamp of the resource within the + given system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp of the last modification of the + resource or its metadata within a given system. + Note: Depending on the source system, not every + modification updates this timestamp. + For example, BigQuery timestamps every metadata + modification but not data or permission changes. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Expiration timestamp of the + resource within the given system. + Currently only applicable to BigQuery resources. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py new file mode 100644 index 00000000..b8314499 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py @@ -0,0 +1,103 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1', + manifest={ + 'UsageStats', + 'UsageSignal', + }, +) + + +class UsageStats(proto.Message): + r"""Detailed statistics on the entry's usage. + + Usage statistics have the following limitations: + + - Only BigQuery tables have them. + - They only include BigQuery query jobs. + - They might be underestimated because wildcard table references + are not yet counted. For more information, see [Querying multiple + tables using a wildcard table] + (https://cloud.google.com/bigquery/docs/querying-wildcard-tables) + + Attributes: + total_completions (float): + The number of successful uses of the + underlying entry. + total_failures (float): + The number of failed attempts to use the + underlying entry. + total_cancellations (float): + The number of cancelled attempts to use the + underlying entry. + total_execution_time_for_completions_millis (float): + Total time spent only on successful uses, in + milliseconds. + """ + + total_completions = proto.Field( + proto.FLOAT, + number=1, + ) + total_failures = proto.Field( + proto.FLOAT, + number=2, + ) + total_cancellations = proto.Field( + proto.FLOAT, + number=3, + ) + total_execution_time_for_completions_millis = proto.Field( + proto.FLOAT, + number=4, + ) + + +class UsageSignal(proto.Message): + r"""The set of all usage signals that Data Catalog stores. + Note: Usually, these signals are updated daily. In rare cases, + an update may fail but will be performed again on the next day. + + Attributes: + update_time (google.protobuf.timestamp_pb2.Timestamp): + The end timestamp of the duration of usage + statistics. + usage_within_time_range (Sequence[google.cloud.datacatalog_v1.types.UsageSignal.UsageWithinTimeRangeEntry]): + Usage statistics over each of the predefined time ranges. + + Supported time ranges are ``{"24H", "7D", "30D"}``. + """ + + update_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + usage_within_time_range = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='UsageStats', + ) + + +__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..0fe4ab2a --- /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', '3.10']) +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/datacatalog_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.9') +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', '3.8', '3.9']) +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.9') +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_datacatalog_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_datacatalog_v1_keywords.py new file mode 100644 index 00000000..33d41aed --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_datacatalog_v1_keywords.py @@ -0,0 +1,216 @@ +#! /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 datacatalogCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_entry': ('parent', 'entry_id', 'entry', ), + 'create_entry_group': ('parent', 'entry_group_id', 'entry_group', ), + 'create_policy_tag': ('parent', 'policy_tag', ), + 'create_tag': ('parent', 'tag', ), + 'create_tag_template': ('parent', 'tag_template_id', 'tag_template', ), + 'create_tag_template_field': ('parent', 'tag_template_field_id', 'tag_template_field', ), + 'create_taxonomy': ('parent', 'taxonomy', ), + 'delete_entry': ('name', ), + 'delete_entry_group': ('name', 'force', ), + 'delete_policy_tag': ('name', ), + 'delete_tag': ('name', ), + 'delete_tag_template': ('name', 'force', ), + 'delete_tag_template_field': ('name', 'force', ), + 'delete_taxonomy': ('name', ), + 'export_taxonomies': ('parent', 'taxonomies', 'serialized_taxonomies', ), + 'get_entry': ('name', ), + 'get_entry_group': ('name', 'read_mask', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_policy_tag': ('name', ), + 'get_tag_template': ('name', ), + 'get_taxonomy': ('name', ), + 'import_taxonomies': ('parent', 'inline_source', 'cross_regional_source', ), + 'list_entries': ('parent', 'page_size', 'page_token', 'read_mask', ), + 'list_entry_groups': ('parent', 'page_size', 'page_token', ), + 'list_policy_tags': ('parent', 'page_size', 'page_token', ), + 'list_tags': ('parent', 'page_size', 'page_token', ), + 'list_taxonomies': ('parent', 'page_size', 'page_token', ), + 'lookup_entry': ('linked_resource', 'sql_resource', 'fully_qualified_name', ), + 'rename_tag_template_field': ('name', 'new_tag_template_field_id', ), + 'rename_tag_template_field_enum_value': ('name', 'new_enum_value_display_name', ), + 'replace_taxonomy': ('name', 'serialized_taxonomy', ), + 'search_catalog': ('scope', 'query', 'page_size', 'page_token', 'order_by', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_entry': ('entry', 'update_mask', ), + 'update_entry_group': ('entry_group', 'update_mask', ), + 'update_policy_tag': ('policy_tag', 'update_mask', ), + 'update_tag': ('tag', 'update_mask', ), + 'update_tag_template': ('tag_template', 'update_mask', ), + 'update_tag_template_field': ('name', 'tag_template_field', 'update_mask', ), + 'update_taxonomy': ('taxonomy', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=datacatalogCallTransformer(), +): + """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 datacatalog 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..f76df593 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,55 @@ +# -*- 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-datacatalog', + 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.28.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.19.4', + 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', + ), + 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/datacatalog_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_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/datacatalog_v1/test_data_catalog.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py new file mode 100644 index 00000000..383f19f6 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py @@ -0,0 +1,8365 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1.services.data_catalog import DataCatalogAsyncClient +from google.cloud.datacatalog_v1.services.data_catalog import DataCatalogClient +from google.cloud.datacatalog_v1.services.data_catalog import pagers +from google.cloud.datacatalog_v1.services.data_catalog import transports +from google.cloud.datacatalog_v1.types import bigquery +from google.cloud.datacatalog_v1.types import common +from google.cloud.datacatalog_v1.types import data_source +from google.cloud.datacatalog_v1.types import datacatalog +from google.cloud.datacatalog_v1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1.types import schema +from google.cloud.datacatalog_v1.types import search +from google.cloud.datacatalog_v1.types import table_spec +from google.cloud.datacatalog_v1.types import tags +from google.cloud.datacatalog_v1.types import timestamps +from google.cloud.datacatalog_v1.types import usage +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataCatalogClient._get_default_mtls_endpoint(None) is None + assert DataCatalogClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DataCatalogClient, + DataCatalogAsyncClient, +]) +def test_data_catalog_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataCatalogGrpcTransport, "grpc"), + (transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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", [ + DataCatalogClient, + DataCatalogAsyncClient, +]) +def test_data_catalog_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 == 'datacatalog.googleapis.com:443' + + +def test_data_catalog_client_get_transport_class(): + transport = DataCatalogClient.get_transport_class() + available_transports = [ + transports.DataCatalogGrpcTransport, + ] + assert transport in available_transports + + transport = DataCatalogClient.get_transport_class("grpc") + assert transport == transports.DataCatalogGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) +@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) +def test_data_catalog_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(DataCatalogClient, '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(DataCatalogClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "true"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "false"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) +@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_catalog_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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(transport=transport_name, 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", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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(transport=transport_name, 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_catalog_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1.services.data_catalog.transports.DataCatalogGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataCatalogClient( + 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_search_catalog(transport: str = 'grpc', request_type=datacatalog.SearchCatalogRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.search_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_search_catalog_from_dict(): + test_search_catalog(request_type=dict) + + +def test_search_catalog_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 = DataCatalogClient( + 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.search_catalog), + '__call__') as call: + client.search_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + +@pytest.mark.asyncio +async def test_search_catalog_async(transport: str = 'grpc_asyncio', request_type=datacatalog.SearchCatalogRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.search_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_search_catalog_async_from_dict(): + await test_search_catalog_async(request_type=dict) + + +def test_search_catalog_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_catalog( + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) + assert args[0].query == 'query_value' + + +def test_search_catalog_flattened_error(): + client = DataCatalogClient( + 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.search_catalog( + datacatalog.SearchCatalogRequest(), + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_value', + ) + + +@pytest.mark.asyncio +async def test_search_catalog_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_catalog( + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) + assert args[0].query == 'query_value' + + +@pytest.mark.asyncio +async def test_search_catalog_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.search_catalog( + datacatalog.SearchCatalogRequest(), + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_value', + ) + + +def test_search_catalog_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.search_catalog(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, search.SearchCatalogResult) + for i in results) + +def test_search_catalog_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_catalog(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_search_catalog_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_catalog(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, search.SearchCatalogResult) + for i in responses) + +@pytest.mark.asyncio +async def test_search_catalog_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_catalog(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_entry_group(transport: str = 'grpc', request_type=datacatalog.CreateEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_entry_group_from_dict(): + test_create_entry_group(request_type=dict) + + +def test_create_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.create_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_create_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_entry_group_async_from_dict(): + await test_create_entry_group_async(request_type=dict) + + +def test_create_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.create_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entry_group( + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' + assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') + + +def test_create_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.CreateEntryGroupRequest(), + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entry_group( + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' + assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') + + +@pytest.mark.asyncio +async def test_create_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.CreateEntryGroupRequest(), + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(name='name_value'), + ) + + +def test_get_entry_group(transport: str = 'grpc', request_type=datacatalog.GetEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_entry_group_from_dict(): + test_get_entry_group(request_type=dict) + + +def test_get_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.get_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_get_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_entry_group_async_from_dict(): + await test_get_entry_group_async(request_type=dict) + + +def test_get_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.get_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entry_group( + name='name_value', + read_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].name == 'name_value' + assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_get_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.GetEntryGroupRequest(), + name='name_value', + read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_get_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entry_group( + name='name_value', + read_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].name == 'name_value' + assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_get_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.GetEntryGroupRequest(), + name='name_value', + read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_entry_group(transport: str = 'grpc', request_type=datacatalog.UpdateEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_entry_group_from_dict(): + test_update_entry_group(request_type=dict) + + +def test_update_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.update_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_update_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_entry_group_async_from_dict(): + await test_update_entry_group_async(request_type=dict) + + +def test_update_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryGroupRequest() + + request.entry_group.name = 'entry_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entry_group.name=entry_group.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryGroupRequest() + + request.entry_group.name = 'entry_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.update_entry_group(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', + 'entry_group.name=entry_group.name/value', + ) in kw['metadata'] + + +def test_update_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entry_group( + entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.UpdateEntryGroupRequest(), + entry_group=datacatalog.EntryGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entry_group( + entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.UpdateEntryGroupRequest(), + entry_group=datacatalog.EntryGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_entry_group(transport: str = 'grpc', request_type=datacatalog.DeleteEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entry_group_from_dict(): + test_delete_entry_group(request_type=dict) + + +def test_delete_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.delete_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_delete_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entry_group_async_from_dict(): + await test_delete_entry_group_async(request_type=dict) + + +def test_delete_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__call__') as call: + call.return_value = None + client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__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_entry_group( + 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_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.DeleteEntryGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__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_entry_group( + 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_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.DeleteEntryGroupRequest(), + name='name_value', + ) + + +def test_list_entry_groups(transport: str = 'grpc', request_type=datacatalog.ListEntryGroupsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntryGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entry_groups_from_dict(): + test_list_entry_groups(request_type=dict) + + +def test_list_entry_groups_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 = DataCatalogClient( + 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_entry_groups), + '__call__') as call: + client.list_entry_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + +@pytest.mark.asyncio +async def test_list_entry_groups_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntryGroupsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntryGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entry_groups_async_from_dict(): + await test_list_entry_groups_async(request_type=dict) + + +def test_list_entry_groups_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntryGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + call.return_value = datacatalog.ListEntryGroupsResponse() + client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_groups_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntryGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) + await client.list_entry_groups(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_entry_groups_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entry_groups( + 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_entry_groups_flattened_error(): + client = DataCatalogClient( + 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_entry_groups( + datacatalog.ListEntryGroupsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_entry_groups_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entry_groups( + 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_entry_groups_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_groups( + datacatalog.ListEntryGroupsRequest(), + parent='parent_value', + ) + + +def test_list_entry_groups_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entry_groups(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, datacatalog.EntryGroup) + for i in results) + +def test_list_entry_groups_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entry_groups(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_entry_groups_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entry_groups(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, datacatalog.EntryGroup) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entry_groups_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entry_groups(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_entry(transport: str = 'grpc', request_type=datacatalog.CreateEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), + ) + response = client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_entry_from_dict(): + test_create_entry(request_type=dict) + + +def test_create_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.create_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + +@pytest.mark.asyncio +async def test_create_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_entry_async_from_dict(): + await test_create_entry_async(request_type=dict) + + +def test_create_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.create_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entry( + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(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].entry_id == 'entry_id_value' + assert args[0].entry == datacatalog.Entry(name='name_value') + + +def test_create_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.CreateEntryRequest(), + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entry( + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(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].entry_id == 'entry_id_value' + assert args[0].entry == datacatalog.Entry(name='name_value') + + +@pytest.mark.asyncio +async def test_create_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.CreateEntryRequest(), + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(name='name_value'), + ) + + +def test_update_entry(transport: str = 'grpc', request_type=datacatalog.UpdateEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), + ) + response = client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_entry_from_dict(): + test_update_entry(request_type=dict) + + +def test_update_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.update_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + +@pytest.mark.asyncio +async def test_update_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_entry_async_from_dict(): + await test_update_entry_async(request_type=dict) + + +def test_update_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryRequest() + + request.entry.name = 'entry.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entry.name=entry.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryRequest() + + request.entry.name = 'entry.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.update_entry(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', + 'entry.name=entry.name/value', + ) in kw['metadata'] + + +def test_update_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entry( + entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.UpdateEntryRequest(), + entry=datacatalog.Entry(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entry( + entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.UpdateEntryRequest(), + entry=datacatalog.Entry(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_entry(transport: str = 'grpc', request_type=datacatalog.DeleteEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entry_from_dict(): + test_delete_entry(request_type=dict) + + +def test_delete_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.delete_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + +@pytest.mark.asyncio +async def test_delete_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entry_async_from_dict(): + await test_delete_entry_async(request_type=dict) + + +def test_delete_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__call__') as call: + call.return_value = None + client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__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_entry( + 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_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.DeleteEntryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__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_entry( + 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_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.DeleteEntryRequest(), + name='name_value', + ) + + +def test_get_entry(transport: str = 'grpc', request_type=datacatalog.GetEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), + ) + response = client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_entry_from_dict(): + test_get_entry(request_type=dict) + + +def test_get_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.get_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + +@pytest.mark.asyncio +async def test_get_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_entry_async_from_dict(): + await test_get_entry_async(request_type=dict) + + +def test_get_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.get_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entry( + 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_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.GetEntryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entry( + 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_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.GetEntryRequest(), + name='name_value', + ) + + +def test_lookup_entry(transport: str = 'grpc', request_type=datacatalog.LookupEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), + ) + response = client.lookup_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_lookup_entry_from_dict(): + test_lookup_entry(request_type=dict) + + +def test_lookup_entry_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 = DataCatalogClient( + 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.lookup_entry), + '__call__') as call: + client.lookup_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + +@pytest.mark.asyncio +async def test_lookup_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.LookupEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + fully_qualified_name='fully_qualified_name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.lookup_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.fully_qualified_name == 'fully_qualified_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_lookup_entry_async_from_dict(): + await test_lookup_entry_async(request_type=dict) + + +def test_list_entries(transport: str = 'grpc', request_type=datacatalog.ListEntriesRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entries_from_dict(): + test_list_entries(request_type=dict) + + +def test_list_entries_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 = DataCatalogClient( + 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_entries), + '__call__') as call: + client.list_entries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + +@pytest.mark.asyncio +async def test_list_entries_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntriesRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entries_async_from_dict(): + await test_list_entries_async(request_type=dict) + + +def test_list_entries_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + call.return_value = datacatalog.ListEntriesResponse() + client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entries_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) + await client.list_entries(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_entries_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entries( + 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_entries_flattened_error(): + client = DataCatalogClient( + 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_entries( + datacatalog.ListEntriesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_entries_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entries( + 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_entries_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entries( + datacatalog.ListEntriesRequest(), + parent='parent_value', + ) + + +def test_list_entries_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entries(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, datacatalog.Entry) + for i in results) + +def test_list_entries_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entries(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_entries_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entries(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, datacatalog.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entries_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entries(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_tag_template(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + ) + response = client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +def test_create_tag_template_from_dict(): + test_create_tag_template(request_type=dict) + + +def test_create_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.create_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_create_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + )) + response = await client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +@pytest.mark.asyncio +async def test_create_tag_template_async_from_dict(): + await test_create_tag_template_async(request_type=dict) + + +def test_create_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.create_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag_template( + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' + assert args[0].tag_template == tags.TagTemplate(name='name_value') + + +def test_create_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.CreateTagTemplateRequest(), + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag_template( + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' + assert args[0].tag_template == tags.TagTemplate(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.CreateTagTemplateRequest(), + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(name='name_value'), + ) + + +def test_get_tag_template(transport: str = 'grpc', request_type=datacatalog.GetTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + ) + response = client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +def test_get_tag_template_from_dict(): + test_get_tag_template(request_type=dict) + + +def test_get_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.get_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_get_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + )) + response = await client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +@pytest.mark.asyncio +async def test_get_tag_template_async_from_dict(): + await test_get_tag_template_async(request_type=dict) + + +def test_get_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.get_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tag_template( + 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_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.GetTagTemplateRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tag_template( + 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_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.GetTagTemplateRequest(), + name='name_value', + ) + + +def test_update_tag_template(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + ) + response = client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +def test_update_tag_template_from_dict(): + test_update_tag_template(request_type=dict) + + +def test_update_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.update_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_update_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + is_publicly_readable=True, + )) + response = await client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_publicly_readable is True + + +@pytest.mark.asyncio +async def test_update_tag_template_async_from_dict(): + await test_update_tag_template_async(request_type=dict) + + +def test_update_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateRequest() + + request.tag_template.name = 'tag_template.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag_template.name=tag_template.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateRequest() + + request.tag_template.name = 'tag_template.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.update_tag_template(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', + 'tag_template.name=tag_template.name/value', + ) in kw['metadata'] + + +def test_update_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_template( + tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.UpdateTagTemplateRequest(), + tag_template=tags.TagTemplate(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_template( + tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.UpdateTagTemplateRequest(), + tag_template=tags.TagTemplate(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_tag_template(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_template_from_dict(): + test_delete_tag_template(request_type=dict) + + +def test_delete_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.delete_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_template_async_from_dict(): + await test_delete_tag_template_async(request_type=dict) + + +def test_delete_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__call__') as call: + call.return_value = None + client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__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_tag_template( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +def test_delete_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.DeleteTagTemplateRequest(), + name='name_value', + force=True, + ) + + +@pytest.mark.asyncio +async def test_delete_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__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_tag_template( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +@pytest.mark.asyncio +async def test_delete_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.DeleteTagTemplateRequest(), + name='name_value', + force=True, + ) + + +def test_create_tag_template_field(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + ) + response = client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +def test_create_tag_template_field_from_dict(): + test_create_tag_template_field(request_type=dict) + + +def test_create_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.create_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_create_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + )) + response = await client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_create_tag_template_field_async_from_dict(): + await test_create_tag_template_field_async(request_type=dict) + + +def test_create_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateFieldRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateFieldRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.create_tag_template_field(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_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag_template_field( + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + + +def test_create_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.CreateTagTemplateFieldRequest(), + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag_template_field( + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.CreateTagTemplateFieldRequest(), + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + ) + + +def test_update_tag_template_field(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + ) + response = client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +def test_update_tag_template_field_from_dict(): + test_update_tag_template_field(request_type=dict) + + +def test_update_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.update_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_update_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + )) + response = await client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_update_tag_template_field_async_from_dict(): + await test_update_tag_template_field_async(request_type=dict) + + +def test_update_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_update_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.update_tag_template_field(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_update_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_template_field( + name='name_value', + tag_template_field=tags.TagTemplateField(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].name == 'name_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.UpdateTagTemplateFieldRequest(), + name='name_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_template_field( + name='name_value', + tag_template_field=tags.TagTemplateField(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].name == 'name_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.UpdateTagTemplateFieldRequest(), + name='name_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_rename_tag_template_field(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + ) + response = client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +def test_rename_tag_template_field_from_dict(): + test_rename_tag_template_field(request_type=dict) + + +def test_rename_tag_template_field_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 = DataCatalogClient( + 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.rename_tag_template_field), + '__call__') as call: + client.rename_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + )) + response = await client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_async_from_dict(): + await test_rename_tag_template_field_async(request_type=dict) + + +def test_rename_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_rename_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.rename_tag_template_field(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_rename_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.rename_tag_template_field( + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' + + +def test_rename_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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.rename_tag_template_field( + datacatalog.RenameTagTemplateFieldRequest(), + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.rename_tag_template_field( + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.rename_tag_template_field( + datacatalog.RenameTagTemplateFieldRequest(), + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + +def test_rename_tag_template_field_enum_value(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldEnumValueRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + ) + response = client.rename_tag_template_field_enum_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +def test_rename_tag_template_field_enum_value_from_dict(): + test_rename_tag_template_field_enum_value(request_type=dict) + + +def test_rename_tag_template_field_enum_value_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 = DataCatalogClient( + 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.rename_tag_template_field_enum_value), + '__call__') as call: + client.rename_tag_template_field_enum_value() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_enum_value_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldEnumValueRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + description='description_value', + order=540, + )) + response = await client.rename_tag_template_field_enum_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.description == 'description_value' + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_enum_value_async_from_dict(): + await test_rename_tag_template_field_enum_value_async(request_type=dict) + + +def test_rename_tag_template_field_enum_value_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldEnumValueRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.rename_tag_template_field_enum_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_rename_tag_template_field_enum_value_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldEnumValueRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.rename_tag_template_field_enum_value(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_rename_tag_template_field_enum_value_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.rename_tag_template_field_enum_value( + name='name_value', + new_enum_value_display_name='new_enum_value_display_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' + assert args[0].new_enum_value_display_name == 'new_enum_value_display_name_value' + + +def test_rename_tag_template_field_enum_value_flattened_error(): + client = DataCatalogClient( + 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.rename_tag_template_field_enum_value( + datacatalog.RenameTagTemplateFieldEnumValueRequest(), + name='name_value', + new_enum_value_display_name='new_enum_value_display_name_value', + ) + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_enum_value_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field_enum_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.rename_tag_template_field_enum_value( + name='name_value', + new_enum_value_display_name='new_enum_value_display_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' + assert args[0].new_enum_value_display_name == 'new_enum_value_display_name_value' + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_enum_value_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.rename_tag_template_field_enum_value( + datacatalog.RenameTagTemplateFieldEnumValueRequest(), + name='name_value', + new_enum_value_display_name='new_enum_value_display_name_value', + ) + + +def test_delete_tag_template_field(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_template_field_from_dict(): + test_delete_tag_template_field(request_type=dict) + + +def test_delete_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.delete_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_async_from_dict(): + await test_delete_tag_template_field_async(request_type=dict) + + +def test_delete_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__call__') as call: + call.return_value = None + client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag_template_field(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_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__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_tag_template_field( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +def test_delete_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.DeleteTagTemplateFieldRequest(), + name='name_value', + force=True, + ) + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__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_tag_template_field( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.DeleteTagTemplateFieldRequest(), + name='name_value', + force=True, + ) + + +def test_create_tag(transport: str = 'grpc', request_type=datacatalog.CreateTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + column='column_value', + ) + response = client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +def test_create_tag_from_dict(): + test_create_tag(request_type=dict) + + +def test_create_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.create_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + +@pytest.mark.asyncio +async def test_create_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + )) + response = await client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +@pytest.mark.asyncio +async def test_create_tag_async_from_dict(): + await test_create_tag_async(request_type=dict) + + +def test_create_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + call.return_value = tags.Tag() + client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + await client.create_tag(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_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag( + parent='parent_value', + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + + +def test_create_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.CreateTagRequest(), + parent='parent_value', + tag=tags.Tag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag( + parent='parent_value', + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.CreateTagRequest(), + parent='parent_value', + tag=tags.Tag(name='name_value'), + ) + + +def test_update_tag(transport: str = 'grpc', request_type=datacatalog.UpdateTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + column='column_value', + ) + response = client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +def test_update_tag_from_dict(): + test_update_tag(request_type=dict) + + +def test_update_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.update_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + +@pytest.mark.asyncio +async def test_update_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + )) + response = await client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +@pytest.mark.asyncio +async def test_update_tag_async_from_dict(): + await test_update_tag_async(request_type=dict) + + +def test_update_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagRequest() + + request.tag.name = 'tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + call.return_value = tags.Tag() + client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag.name=tag.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagRequest() + + request.tag.name = 'tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + await client.update_tag(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', + 'tag.name=tag.name/value', + ) in kw['metadata'] + + +def test_update_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag( + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.UpdateTagRequest(), + tag=tags.Tag(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag( + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.UpdateTagRequest(), + tag=tags.Tag(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_tag(transport: str = 'grpc', request_type=datacatalog.DeleteTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_from_dict(): + test_delete_tag(request_type=dict) + + +def test_delete_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.delete_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_async_from_dict(): + await test_delete_tag_async(request_type=dict) + + +def test_delete_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__call__') as call: + call.return_value = None + client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag(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_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__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_tag( + 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_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.DeleteTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__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_tag( + 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_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.DeleteTagRequest(), + name='name_value', + ) + + +def test_list_tags(transport: str = 'grpc', request_type=datacatalog.ListTagsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tags_from_dict(): + test_list_tags(request_type=dict) + + +def test_list_tags_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 = DataCatalogClient( + 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_tags), + '__call__') as call: + client.list_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + +@pytest.mark.asyncio +async def test_list_tags_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListTagsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tags_async_from_dict(): + await test_list_tags_async(request_type=dict) + + +def test_list_tags_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + call.return_value = datacatalog.ListTagsResponse() + client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tags_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) + await client.list_tags(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_tags_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tags( + 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_tags_flattened_error(): + client = DataCatalogClient( + 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_tags( + datacatalog.ListTagsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_tags_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tags( + 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_tags_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tags( + datacatalog.ListTagsRequest(), + parent='parent_value', + ) + + +def test_list_tags_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_tags(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, tags.Tag) + for i in results) + +def test_list_tags_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tags(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_tags_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tags(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, tags.Tag) + for i in responses) + +@pytest.mark.asyncio +async def test_list_tags_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_tags(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataCatalogClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_set_iam_policy_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy(request={ + 'resource': 'resource_value', + 'policy': policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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].resource == 'resource_value' + + +def test_set_iam_policy_flattened_error(): + client = DataCatalogClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_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].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataCatalogClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_get_iam_policy_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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].resource == 'resource_value' + + +def test_get_iam_policy_flattened_error(): + client = DataCatalogClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_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].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = DataCatalogClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + )) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_test_iam_permissions_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions(request={ + 'resource': 'resource_value', + 'permissions': ['permissions_value'], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataCatalogClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataCatalogGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataCatalogGrpcTransport, + transports.DataCatalogGrpcAsyncIOTransport, +]) +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 = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataCatalogGrpcTransport, + ) + +def test_data_catalog_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataCatalogTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_catalog_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataCatalogTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search_catalog', + 'create_entry_group', + 'get_entry_group', + 'update_entry_group', + 'delete_entry_group', + 'list_entry_groups', + 'create_entry', + 'update_entry', + 'delete_entry', + 'get_entry', + 'lookup_entry', + 'list_entries', + 'create_tag_template', + 'get_tag_template', + 'update_tag_template', + 'delete_tag_template', + 'create_tag_template_field', + 'update_tag_template_field', + 'rename_tag_template_field', + 'rename_tag_template_field_enum_value', + 'delete_tag_template_field', + 'create_tag', + 'update_tag', + 'delete_tag', + 'list_tags', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_data_catalog_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.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataCatalogTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_data_catalog_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.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataCatalogTransport() + adc.assert_called_once() + + +def test_data_catalog_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) + DataCatalogClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataCatalogGrpcTransport, + transports.DataCatalogGrpcAsyncIOTransport, + ], +) +def test_data_catalog_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,grpc_helpers", + [ + (transports.DataCatalogGrpcTransport, grpc_helpers), + (transports.DataCatalogGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_catalog_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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_catalog_host_no_port(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_data_catalog_host_with_port(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_data_catalog_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataCatalogGrpcTransport( + 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_catalog_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataCatalogGrpcAsyncIOTransport( + 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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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_entry_path(): + project = "squid" + location = "clam" + entry_group = "whelk" + entry = "octopus" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) + actual = DataCatalogClient.entry_path(project, location, entry_group, entry) + assert expected == actual + + +def test_parse_entry_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "entry_group": "cuttlefish", + "entry": "mussel", + } + path = DataCatalogClient.entry_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_entry_path(path) + assert expected == actual + +def test_entry_group_path(): + project = "winkle" + location = "nautilus" + entry_group = "scallop" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) + actual = DataCatalogClient.entry_group_path(project, location, entry_group) + assert expected == actual + + +def test_parse_entry_group_path(): + expected = { + "project": "abalone", + "location": "squid", + "entry_group": "clam", + } + path = DataCatalogClient.entry_group_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_entry_group_path(path) + assert expected == actual + +def test_tag_path(): + project = "whelk" + location = "octopus" + entry_group = "oyster" + entry = "nudibranch" + tag = "cuttlefish" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) + actual = DataCatalogClient.tag_path(project, location, entry_group, entry, tag) + assert expected == actual + + +def test_parse_tag_path(): + expected = { + "project": "mussel", + "location": "winkle", + "entry_group": "nautilus", + "entry": "scallop", + "tag": "abalone", + } + path = DataCatalogClient.tag_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_path(path) + assert expected == actual + +def test_tag_template_path(): + project = "squid" + location = "clam" + tag_template = "whelk" + expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) + actual = DataCatalogClient.tag_template_path(project, location, tag_template) + assert expected == actual + + +def test_parse_tag_template_path(): + expected = { + "project": "octopus", + "location": "oyster", + "tag_template": "nudibranch", + } + path = DataCatalogClient.tag_template_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_template_path(path) + assert expected == actual + +def test_tag_template_field_path(): + project = "cuttlefish" + location = "mussel" + tag_template = "winkle" + field = "nautilus" + expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) + actual = DataCatalogClient.tag_template_field_path(project, location, tag_template, field) + assert expected == actual + + +def test_parse_tag_template_field_path(): + expected = { + "project": "scallop", + "location": "abalone", + "tag_template": "squid", + "field": "clam", + } + path = DataCatalogClient.tag_template_field_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_template_field_path(path) + assert expected == actual + +def test_tag_template_field_enum_value_path(): + project = "whelk" + location = "octopus" + tag_template = "oyster" + tag_template_field_id = "nudibranch" + enum_value_display_name = "cuttlefish" + expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{tag_template_field_id}/enumValues/{enum_value_display_name}".format(project=project, location=location, tag_template=tag_template, tag_template_field_id=tag_template_field_id, enum_value_display_name=enum_value_display_name, ) + actual = DataCatalogClient.tag_template_field_enum_value_path(project, location, tag_template, tag_template_field_id, enum_value_display_name) + assert expected == actual + + +def test_parse_tag_template_field_enum_value_path(): + expected = { + "project": "mussel", + "location": "winkle", + "tag_template": "nautilus", + "tag_template_field_id": "scallop", + "enum_value_display_name": "abalone", + } + path = DataCatalogClient.tag_template_field_enum_value_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_template_field_enum_value_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataCatalogClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DataCatalogClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataCatalogClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DataCatalogClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataCatalogClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DataCatalogClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DataCatalogClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DataCatalogClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DataCatalogClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DataCatalogClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.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.DataCatalogTransport, '_prep_wrapped_messages') as prep: + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataCatalogTransport, '_prep_wrapped_messages') as prep: + transport_class = DataCatalogClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py new file mode 100644 index 00000000..248c1a93 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py @@ -0,0 +1,4247 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1.services.policy_tag_manager import PolicyTagManagerAsyncClient +from google.cloud.datacatalog_v1.services.policy_tag_manager import PolicyTagManagerClient +from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1.services.policy_tag_manager import transports +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PolicyTagManagerClient._get_default_mtls_endpoint(None) is None + assert PolicyTagManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PolicyTagManagerClient, + PolicyTagManagerAsyncClient, +]) +def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PolicyTagManagerGrpcTransport, "grpc"), + (transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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", [ + PolicyTagManagerClient, + PolicyTagManagerAsyncClient, +]) +def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_client_get_transport_class(): + transport = PolicyTagManagerClient.get_transport_class() + available_transports = [ + transports.PolicyTagManagerGrpcTransport, + ] + assert transport in available_transports + + transport = PolicyTagManagerClient.get_transport_class("grpc") + assert transport == transports.PolicyTagManagerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) +@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) +def test_policy_tag_manager_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(PolicyTagManagerClient, '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(PolicyTagManagerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "true"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "false"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) +@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_policy_tag_manager_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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(transport=transport_name, 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", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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(transport=transport_name, 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_policy_tag_manager_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PolicyTagManagerClient( + 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_create_taxonomy(transport: str = 'grpc', request_type=policytagmanager.CreateTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_create_taxonomy_from_dict(): + test_create_taxonomy(request_type=dict) + + +def test_create_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.create_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_create_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreateTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_create_taxonomy_async_from_dict(): + await test_create_taxonomy_async(request_type=dict) + + +def test_create_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreateTaxonomyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreateTaxonomyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.create_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_taxonomy( + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +def test_create_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.CreateTaxonomyRequest(), + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_taxonomy( + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +@pytest.mark.asyncio +async def test_create_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.CreateTaxonomyRequest(), + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +def test_delete_taxonomy(transport: str = 'grpc', request_type=policytagmanager.DeleteTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_taxonomy_from_dict(): + test_delete_taxonomy(request_type=dict) + + +def test_delete_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.delete_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_delete_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeleteTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_taxonomy_async_from_dict(): + await test_delete_taxonomy_async(request_type=dict) + + +def test_delete_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeleteTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__call__') as call: + call.return_value = None + client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeleteTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__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_taxonomy( + 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_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.DeleteTaxonomyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__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_taxonomy( + 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_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.DeleteTaxonomyRequest(), + name='name_value', + ) + + +def test_update_taxonomy(transport: str = 'grpc', request_type=policytagmanager.UpdateTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_update_taxonomy_from_dict(): + test_update_taxonomy(request_type=dict) + + +def test_update_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.update_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_update_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdateTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_update_taxonomy_async_from_dict(): + await test_update_taxonomy_async(request_type=dict) + + +def test_update_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdateTaxonomyRequest() + + request.taxonomy.name = 'taxonomy.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'taxonomy.name=taxonomy.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdateTaxonomyRequest() + + request.taxonomy.name = 'taxonomy.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.update_taxonomy(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', + 'taxonomy.name=taxonomy.name/value', + ) in kw['metadata'] + + +def test_update_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_taxonomy( + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +def test_update_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.UpdateTaxonomyRequest(), + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_taxonomy( + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +@pytest.mark.asyncio +async def test_update_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.UpdateTaxonomyRequest(), + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +def test_list_taxonomies(transport: str = 'grpc', request_type=policytagmanager.ListTaxonomiesRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTaxonomiesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_taxonomies_from_dict(): + test_list_taxonomies(request_type=dict) + + +def test_list_taxonomies_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 = PolicyTagManagerClient( + 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_taxonomies), + '__call__') as call: + client.list_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_list_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListTaxonomiesRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTaxonomiesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_taxonomies_async_from_dict(): + await test_list_taxonomies_async(request_type=dict) + + +def test_list_taxonomies_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + call.return_value = policytagmanager.ListTaxonomiesResponse() + client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_taxonomies_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) + await client.list_taxonomies(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_taxonomies_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_taxonomies( + 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_taxonomies_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomies( + policytagmanager.ListTaxonomiesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_taxonomies_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_taxonomies( + 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_taxonomies_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomies( + policytagmanager.ListTaxonomiesRequest(), + parent='parent_value', + ) + + +def test_list_taxonomies_pager(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_taxonomies(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, policytagmanager.Taxonomy) + for i in results) + +def test_list_taxonomies_pages(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_taxonomies(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_taxonomies_async_pager(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_taxonomies(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, policytagmanager.Taxonomy) + for i in responses) + +@pytest.mark.asyncio +async def test_list_taxonomies_async_pages(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_taxonomies(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_taxonomy(transport: str = 'grpc', request_type=policytagmanager.GetTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_get_taxonomy_from_dict(): + test_get_taxonomy(request_type=dict) + + +def test_get_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.get_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_get_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_get_taxonomy_async_from_dict(): + await test_get_taxonomy_async(request_type=dict) + + +def test_get_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.get_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_taxonomy( + 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_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.GetTaxonomyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_taxonomy( + 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_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.GetTaxonomyRequest(), + name='name_value', + ) + + +def test_create_policy_tag(transport: str = 'grpc', request_type=policytagmanager.CreatePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_create_policy_tag_from_dict(): + test_create_policy_tag(request_type=dict) + + +def test_create_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.create_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_create_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreatePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_create_policy_tag_async_from_dict(): + await test_create_policy_tag_async(request_type=dict) + + +def test_create_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreatePolicyTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreatePolicyTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.create_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_policy_tag( + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +def test_create_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.CreatePolicyTagRequest(), + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_policy_tag( + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +@pytest.mark.asyncio +async def test_create_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.CreatePolicyTagRequest(), + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +def test_delete_policy_tag(transport: str = 'grpc', request_type=policytagmanager.DeletePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_policy_tag_from_dict(): + test_delete_policy_tag(request_type=dict) + + +def test_delete_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.delete_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_delete_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeletePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_policy_tag_async_from_dict(): + await test_delete_policy_tag_async(request_type=dict) + + +def test_delete_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeletePolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__call__') as call: + call.return_value = None + client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeletePolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__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_policy_tag( + 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_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.DeletePolicyTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__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_policy_tag( + 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_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.DeletePolicyTagRequest(), + name='name_value', + ) + + +def test_update_policy_tag(transport: str = 'grpc', request_type=policytagmanager.UpdatePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_update_policy_tag_from_dict(): + test_update_policy_tag(request_type=dict) + + +def test_update_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.update_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_update_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdatePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_update_policy_tag_async_from_dict(): + await test_update_policy_tag_async(request_type=dict) + + +def test_update_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdatePolicyTagRequest() + + request.policy_tag.name = 'policy_tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'policy_tag.name=policy_tag.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdatePolicyTagRequest() + + request.policy_tag.name = 'policy_tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.update_policy_tag(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', + 'policy_tag.name=policy_tag.name/value', + ) in kw['metadata'] + + +def test_update_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_policy_tag( + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +def test_update_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.UpdatePolicyTagRequest(), + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_policy_tag( + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +@pytest.mark.asyncio +async def test_update_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.UpdatePolicyTagRequest(), + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +def test_list_policy_tags(transport: str = 'grpc', request_type=policytagmanager.ListPolicyTagsRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyTagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_policy_tags_from_dict(): + test_list_policy_tags(request_type=dict) + + +def test_list_policy_tags_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 = PolicyTagManagerClient( + 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_policy_tags), + '__call__') as call: + client.list_policy_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + +@pytest.mark.asyncio +async def test_list_policy_tags_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListPolicyTagsRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyTagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_policy_tags_async_from_dict(): + await test_list_policy_tags_async(request_type=dict) + + +def test_list_policy_tags_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListPolicyTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + call.return_value = policytagmanager.ListPolicyTagsResponse() + client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_policy_tags_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListPolicyTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) + await client.list_policy_tags(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_policy_tags_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_policy_tags( + 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_policy_tags_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tags( + policytagmanager.ListPolicyTagsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_policy_tags_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_policy_tags( + 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_policy_tags_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tags( + policytagmanager.ListPolicyTagsRequest(), + parent='parent_value', + ) + + +def test_list_policy_tags_pager(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_policy_tags(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, policytagmanager.PolicyTag) + for i in results) + +def test_list_policy_tags_pages(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_policy_tags(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_policy_tags_async_pager(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_policy_tags(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, policytagmanager.PolicyTag) + for i in responses) + +@pytest.mark.asyncio +async def test_list_policy_tags_async_pages(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_policy_tags(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_policy_tag(transport: str = 'grpc', request_type=policytagmanager.GetPolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_get_policy_tag_from_dict(): + test_get_policy_tag(request_type=dict) + + +def test_get_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.get_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + +@pytest.mark.asyncio +async def test_get_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetPolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_get_policy_tag_async_from_dict(): + await test_get_policy_tag_async(request_type=dict) + + +def test_get_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetPolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetPolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.get_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_policy_tag( + 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_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.GetPolicyTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_policy_tag( + 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_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.GetPolicyTagRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PolicyTagManagerClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_get_iam_policy_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PolicyTagManagerClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_set_iam_policy_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy(request={ + 'resource': 'resource_value', + 'policy': policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = PolicyTagManagerClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + )) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_test_iam_permissions_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions(request={ + 'resource': 'resource_value', + 'permissions': ['permissions_value'], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PolicyTagManagerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PolicyTagManagerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PolicyTagManagerGrpcTransport, + transports.PolicyTagManagerGrpcAsyncIOTransport, +]) +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 = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PolicyTagManagerGrpcTransport, + ) + +def test_policy_tag_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PolicyTagManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_policy_tag_manager_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PolicyTagManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_taxonomy', + 'delete_taxonomy', + 'update_taxonomy', + 'list_taxonomies', + 'get_taxonomy', + 'create_policy_tag', + 'delete_policy_tag', + 'update_policy_tag', + 'list_policy_tags', + 'get_policy_tag', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_policy_tag_manager_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.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_policy_tag_manager_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.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerTransport() + adc.assert_called_once() + + +def test_policy_tag_manager_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) + PolicyTagManagerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyTagManagerGrpcTransport, + transports.PolicyTagManagerGrpcAsyncIOTransport, + ], +) +def test_policy_tag_manager_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,grpc_helpers", + [ + (transports.PolicyTagManagerGrpcTransport, grpc_helpers), + (transports.PolicyTagManagerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_policy_tag_manager_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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_policy_tag_manager_host_no_port(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_host_with_port(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_policy_tag_manager_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerGrpcTransport( + 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_policy_tag_manager_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerGrpcAsyncIOTransport( + 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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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_policy_tag_path(): + project = "squid" + location = "clam" + taxonomy = "whelk" + policy_tag = "octopus" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) + actual = PolicyTagManagerClient.policy_tag_path(project, location, taxonomy, policy_tag) + assert expected == actual + + +def test_parse_policy_tag_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "taxonomy": "cuttlefish", + "policy_tag": "mussel", + } + path = PolicyTagManagerClient.policy_tag_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_policy_tag_path(path) + assert expected == actual + +def test_taxonomy_path(): + project = "winkle" + location = "nautilus" + taxonomy = "scallop" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + actual = PolicyTagManagerClient.taxonomy_path(project, location, taxonomy) + assert expected == actual + + +def test_parse_taxonomy_path(): + expected = { + "project": "abalone", + "location": "squid", + "taxonomy": "clam", + } + path = PolicyTagManagerClient.taxonomy_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_taxonomy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PolicyTagManagerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = PolicyTagManagerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = PolicyTagManagerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = PolicyTagManagerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PolicyTagManagerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = PolicyTagManagerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = PolicyTagManagerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = PolicyTagManagerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.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 = PolicyTagManagerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = PolicyTagManagerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.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.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: + transport_class = PolicyTagManagerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py new file mode 100644 index 00000000..0028b014 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py @@ -0,0 +1,1379 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient +from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient +from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import transports +from google.cloud.datacatalog_v1.types import policytagmanager +from google.cloud.datacatalog_v1.types import policytagmanagerserialization +from google.cloud.datacatalog_v1.types import timestamps +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(None) is None + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PolicyTagManagerSerializationClient, + PolicyTagManagerSerializationAsyncClient, +]) +def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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", [ + PolicyTagManagerSerializationClient, + PolicyTagManagerSerializationAsyncClient, +]) +def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_serialization_client_get_transport_class(): + transport = PolicyTagManagerSerializationClient.get_transport_class() + available_transports = [ + transports.PolicyTagManagerSerializationGrpcTransport, + ] + assert transport in available_transports + + transport = PolicyTagManagerSerializationClient.get_transport_class("grpc") + assert transport == transports.PolicyTagManagerSerializationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) +@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) +def test_policy_tag_manager_serialization_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(PolicyTagManagerSerializationClient, '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(PolicyTagManagerSerializationClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "true"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "false"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) +@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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_policy_tag_manager_serialization_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PolicyTagManagerSerializationClient( + 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_replace_taxonomy(transport: str = 'grpc', request_type=policytagmanagerserialization.ReplaceTaxonomyRequest): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.replace_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_replace_taxonomy_from_dict(): + test_replace_taxonomy(request_type=dict) + + +def test_replace_taxonomy_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 = PolicyTagManagerSerializationClient( + 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.replace_taxonomy), + '__call__') as call: + client.replace_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_replace_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ReplaceTaxonomyRequest): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + policy_tag_count=1715, + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.replace_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.policy_tag_count == 1715 + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_replace_taxonomy_async_from_dict(): + await test_replace_taxonomy_async(request_type=dict) + + +def test_replace_taxonomy_field_headers(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ReplaceTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.replace_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_replace_taxonomy_field_headers_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ReplaceTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.replace_taxonomy(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_import_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse( + ) + response = client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) + + +def test_import_taxonomies_from_dict(): + test_import_taxonomies(request_type=dict) + + +def test_import_taxonomies_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 = PolicyTagManagerSerializationClient( + 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.import_taxonomies), + '__call__') as call: + client.import_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_import_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse( + )) + response = await client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) + + +@pytest.mark.asyncio +async def test_import_taxonomies_async_from_dict(): + await test_import_taxonomies_async(request_type=dict) + + +def test_import_taxonomies_field_headers(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ImportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse() + client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_import_taxonomies_field_headers_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ImportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse()) + await client.import_taxonomies(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_export_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse( + ) + response = client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) + + +def test_export_taxonomies_from_dict(): + test_export_taxonomies(request_type=dict) + + +def test_export_taxonomies_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 = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + client.export_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_export_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse( + )) + response = await client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) + + +@pytest.mark.asyncio +async def test_export_taxonomies_async_from_dict(): + await test_export_taxonomies_async(request_type=dict) + + +def test_export_taxonomies_field_headers(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ExportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse() + client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_export_taxonomies_field_headers_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ExportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse()) + await client.export_taxonomies(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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PolicyTagManagerSerializationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PolicyTagManagerSerializationGrpcTransport, + transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, +]) +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 = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PolicyTagManagerSerializationGrpcTransport, + ) + +def test_policy_tag_manager_serialization_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PolicyTagManagerSerializationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_policy_tag_manager_serialization_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PolicyTagManagerSerializationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'replace_taxonomy', + 'import_taxonomies', + 'export_taxonomies', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_policy_tag_manager_serialization_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.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerSerializationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_policy_tag_manager_serialization_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.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerSerializationTransport() + adc.assert_called_once() + + +def test_policy_tag_manager_serialization_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) + PolicyTagManagerSerializationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyTagManagerSerializationGrpcTransport, + transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, + ], +) +def test_policy_tag_manager_serialization_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,grpc_helpers", + [ + (transports.PolicyTagManagerSerializationGrpcTransport, grpc_helpers), + (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_policy_tag_manager_serialization_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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_policy_tag_manager_serialization_host_no_port(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_serialization_host_with_port(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_policy_tag_manager_serialization_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + 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_policy_tag_manager_serialization_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( + 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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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_taxonomy_path(): + project = "squid" + location = "clam" + taxonomy = "whelk" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + actual = PolicyTagManagerSerializationClient.taxonomy_path(project, location, taxonomy) + assert expected == actual + + +def test_parse_taxonomy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "taxonomy": "nudibranch", + } + path = PolicyTagManagerSerializationClient.taxonomy_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_taxonomy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PolicyTagManagerSerializationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = PolicyTagManagerSerializationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = PolicyTagManagerSerializationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = PolicyTagManagerSerializationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PolicyTagManagerSerializationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = PolicyTagManagerSerializationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = PolicyTagManagerSerializationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = PolicyTagManagerSerializationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = PolicyTagManagerSerializationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = PolicyTagManagerSerializationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.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.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: + transport_class = PolicyTagManagerSerializationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 00000000..ac5fa2e9 --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/datacatalog/__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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 00000000..0e9fef34 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/datacatalog *.py +recursive-include google/cloud/datacatalog_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 00000000..8f53b244 --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Datacatalog 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 Datacatalog 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 00000000..67b364b2 --- /dev/null +++ b/owl-bot-staging/v1beta1/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-datacatalog 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-datacatalog" +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-datacatalog-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-datacatalog.tex", + u"google-cloud-datacatalog 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-datacatalog", + u"Google Cloud Datacatalog 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-datacatalog", + u"google-cloud-datacatalog Documentation", + author, + "google-cloud-datacatalog", + "GAPIC library for Google Cloud Datacatalog 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/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst new file mode 100644 index 00000000..82ca26f3 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst @@ -0,0 +1,10 @@ +DataCatalog +----------------------------- + +.. automodule:: google.cloud.datacatalog_v1beta1.services.data_catalog + :members: + :inherited-members: + +.. automodule:: google.cloud.datacatalog_v1beta1.services.data_catalog.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst new file mode 100644 index 00000000..8971945c --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst @@ -0,0 +1,10 @@ +PolicyTagManager +---------------------------------- + +.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager + :members: + :inherited-members: + +.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst new file mode 100644 index 00000000..aed4c56c --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst @@ -0,0 +1,6 @@ +PolicyTagManagerSerialization +----------------------------------------------- + +.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst new file mode 100644 index 00000000..4f762e1c --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst @@ -0,0 +1,8 @@ +Services for Google Cloud Datacatalog v1beta1 API +================================================= +.. toctree:: + :maxdepth: 2 + + data_catalog + policy_tag_manager + policy_tag_manager_serialization diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst new file mode 100644 index 00000000..687d8391 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Datacatalog v1beta1 API +============================================== + +.. automodule:: google.cloud.datacatalog_v1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 00000000..ae7dac5f --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + datacatalog_v1beta1/services + datacatalog_v1beta1/types diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py new file mode 100644 index 00000000..8e9095b9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py @@ -0,0 +1,171 @@ +# -*- 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.datacatalog_v1beta1.services.data_catalog.client import DataCatalogClient +from google.cloud.datacatalog_v1beta1.services.data_catalog.async_client import DataCatalogAsyncClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager.client import PolicyTagManagerClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager.async_client import PolicyTagManagerAsyncClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.client import PolicyTagManagerSerializationClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.async_client import PolicyTagManagerSerializationAsyncClient + +from google.cloud.datacatalog_v1beta1.types.common import IntegratedSystem +from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateEntryGroupRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateEntryRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagTemplateFieldRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagTemplateRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteEntryGroupRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteEntryRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagTemplateFieldRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagTemplateRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import Entry +from google.cloud.datacatalog_v1beta1.types.datacatalog import EntryGroup +from google.cloud.datacatalog_v1beta1.types.datacatalog import GetEntryGroupRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import GetEntryRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import GetTagTemplateRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntriesRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntriesResponse +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntryGroupsRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntryGroupsResponse +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListTagsRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import ListTagsResponse +from google.cloud.datacatalog_v1beta1.types.datacatalog import LookupEntryRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import RenameTagTemplateFieldRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import SearchCatalogRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import SearchCatalogResponse +from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateEntryGroupRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateEntryRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagTemplateFieldRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagTemplateRequest +from google.cloud.datacatalog_v1beta1.types.datacatalog import EntryType +from google.cloud.datacatalog_v1beta1.types.gcs_fileset_spec import GcsFilesetSpec +from google.cloud.datacatalog_v1beta1.types.gcs_fileset_spec import GcsFileSpec +from google.cloud.datacatalog_v1beta1.types.policytagmanager import CreatePolicyTagRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import CreateTaxonomyRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import DeletePolicyTagRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import DeleteTaxonomyRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import GetPolicyTagRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import GetTaxonomyRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListPolicyTagsRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListPolicyTagsResponse +from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListTaxonomiesRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListTaxonomiesResponse +from google.cloud.datacatalog_v1beta1.types.policytagmanager import PolicyTag +from google.cloud.datacatalog_v1beta1.types.policytagmanager import Taxonomy +from google.cloud.datacatalog_v1beta1.types.policytagmanager import UpdatePolicyTagRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanager import UpdateTaxonomyRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ExportTaxonomiesRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ExportTaxonomiesResponse +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ImportTaxonomiesRequest +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ImportTaxonomiesResponse +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import InlineSource +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import SerializedPolicyTag +from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import SerializedTaxonomy +from google.cloud.datacatalog_v1beta1.types.schema import ColumnSchema +from google.cloud.datacatalog_v1beta1.types.schema import Schema +from google.cloud.datacatalog_v1beta1.types.search import SearchCatalogResult +from google.cloud.datacatalog_v1beta1.types.search import SearchResultType +from google.cloud.datacatalog_v1beta1.types.table_spec import BigQueryDateShardedSpec +from google.cloud.datacatalog_v1beta1.types.table_spec import BigQueryTableSpec +from google.cloud.datacatalog_v1beta1.types.table_spec import TableSpec +from google.cloud.datacatalog_v1beta1.types.table_spec import ViewSpec +from google.cloud.datacatalog_v1beta1.types.table_spec import TableSourceType +from google.cloud.datacatalog_v1beta1.types.tags import FieldType +from google.cloud.datacatalog_v1beta1.types.tags import Tag +from google.cloud.datacatalog_v1beta1.types.tags import TagField +from google.cloud.datacatalog_v1beta1.types.tags import TagTemplate +from google.cloud.datacatalog_v1beta1.types.tags import TagTemplateField +from google.cloud.datacatalog_v1beta1.types.timestamps import SystemTimestamps + +__all__ = ('DataCatalogClient', + 'DataCatalogAsyncClient', + 'PolicyTagManagerClient', + 'PolicyTagManagerAsyncClient', + 'PolicyTagManagerSerializationClient', + 'PolicyTagManagerSerializationAsyncClient', + 'IntegratedSystem', + 'CreateEntryGroupRequest', + 'CreateEntryRequest', + 'CreateTagRequest', + 'CreateTagTemplateFieldRequest', + 'CreateTagTemplateRequest', + 'DeleteEntryGroupRequest', + 'DeleteEntryRequest', + 'DeleteTagRequest', + 'DeleteTagTemplateFieldRequest', + 'DeleteTagTemplateRequest', + 'Entry', + 'EntryGroup', + 'GetEntryGroupRequest', + 'GetEntryRequest', + 'GetTagTemplateRequest', + 'ListEntriesRequest', + 'ListEntriesResponse', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'ListTagsRequest', + 'ListTagsResponse', + 'LookupEntryRequest', + 'RenameTagTemplateFieldRequest', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'UpdateEntryGroupRequest', + 'UpdateEntryRequest', + 'UpdateTagRequest', + 'UpdateTagTemplateFieldRequest', + 'UpdateTagTemplateRequest', + 'EntryType', + 'GcsFilesetSpec', + 'GcsFileSpec', + 'CreatePolicyTagRequest', + 'CreateTaxonomyRequest', + 'DeletePolicyTagRequest', + 'DeleteTaxonomyRequest', + 'GetPolicyTagRequest', + 'GetTaxonomyRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'PolicyTag', + 'Taxonomy', + 'UpdatePolicyTagRequest', + 'UpdateTaxonomyRequest', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + 'ImportTaxonomiesRequest', + 'ImportTaxonomiesResponse', + 'InlineSource', + 'SerializedPolicyTag', + 'SerializedTaxonomy', + 'ColumnSchema', + 'Schema', + 'SearchCatalogResult', + 'SearchResultType', + 'BigQueryDateShardedSpec', + 'BigQueryTableSpec', + 'TableSpec', + 'ViewSpec', + 'TableSourceType', + 'FieldType', + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'SystemTimestamps', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed b/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed new file mode 100644 index 00000000..bb4088a3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py new file mode 100644 index 00000000..dc3c7a23 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py @@ -0,0 +1,172 @@ +# -*- 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_catalog import DataCatalogClient +from .services.data_catalog import DataCatalogAsyncClient +from .services.policy_tag_manager import PolicyTagManagerClient +from .services.policy_tag_manager import PolicyTagManagerAsyncClient +from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient +from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient + +from .types.common import IntegratedSystem +from .types.datacatalog import CreateEntryGroupRequest +from .types.datacatalog import CreateEntryRequest +from .types.datacatalog import CreateTagRequest +from .types.datacatalog import CreateTagTemplateFieldRequest +from .types.datacatalog import CreateTagTemplateRequest +from .types.datacatalog import DeleteEntryGroupRequest +from .types.datacatalog import DeleteEntryRequest +from .types.datacatalog import DeleteTagRequest +from .types.datacatalog import DeleteTagTemplateFieldRequest +from .types.datacatalog import DeleteTagTemplateRequest +from .types.datacatalog import Entry +from .types.datacatalog import EntryGroup +from .types.datacatalog import GetEntryGroupRequest +from .types.datacatalog import GetEntryRequest +from .types.datacatalog import GetTagTemplateRequest +from .types.datacatalog import ListEntriesRequest +from .types.datacatalog import ListEntriesResponse +from .types.datacatalog import ListEntryGroupsRequest +from .types.datacatalog import ListEntryGroupsResponse +from .types.datacatalog import ListTagsRequest +from .types.datacatalog import ListTagsResponse +from .types.datacatalog import LookupEntryRequest +from .types.datacatalog import RenameTagTemplateFieldRequest +from .types.datacatalog import SearchCatalogRequest +from .types.datacatalog import SearchCatalogResponse +from .types.datacatalog import UpdateEntryGroupRequest +from .types.datacatalog import UpdateEntryRequest +from .types.datacatalog import UpdateTagRequest +from .types.datacatalog import UpdateTagTemplateFieldRequest +from .types.datacatalog import UpdateTagTemplateRequest +from .types.datacatalog import EntryType +from .types.gcs_fileset_spec import GcsFilesetSpec +from .types.gcs_fileset_spec import GcsFileSpec +from .types.policytagmanager import CreatePolicyTagRequest +from .types.policytagmanager import CreateTaxonomyRequest +from .types.policytagmanager import DeletePolicyTagRequest +from .types.policytagmanager import DeleteTaxonomyRequest +from .types.policytagmanager import GetPolicyTagRequest +from .types.policytagmanager import GetTaxonomyRequest +from .types.policytagmanager import ListPolicyTagsRequest +from .types.policytagmanager import ListPolicyTagsResponse +from .types.policytagmanager import ListTaxonomiesRequest +from .types.policytagmanager import ListTaxonomiesResponse +from .types.policytagmanager import PolicyTag +from .types.policytagmanager import Taxonomy +from .types.policytagmanager import UpdatePolicyTagRequest +from .types.policytagmanager import UpdateTaxonomyRequest +from .types.policytagmanagerserialization import ExportTaxonomiesRequest +from .types.policytagmanagerserialization import ExportTaxonomiesResponse +from .types.policytagmanagerserialization import ImportTaxonomiesRequest +from .types.policytagmanagerserialization import ImportTaxonomiesResponse +from .types.policytagmanagerserialization import InlineSource +from .types.policytagmanagerserialization import SerializedPolicyTag +from .types.policytagmanagerserialization import SerializedTaxonomy +from .types.schema import ColumnSchema +from .types.schema import Schema +from .types.search import SearchCatalogResult +from .types.search import SearchResultType +from .types.table_spec import BigQueryDateShardedSpec +from .types.table_spec import BigQueryTableSpec +from .types.table_spec import TableSpec +from .types.table_spec import ViewSpec +from .types.table_spec import TableSourceType +from .types.tags import FieldType +from .types.tags import Tag +from .types.tags import TagField +from .types.tags import TagTemplate +from .types.tags import TagTemplateField +from .types.timestamps import SystemTimestamps + +__all__ = ( + 'DataCatalogAsyncClient', + 'PolicyTagManagerAsyncClient', + 'PolicyTagManagerSerializationAsyncClient', +'BigQueryDateShardedSpec', +'BigQueryTableSpec', +'ColumnSchema', +'CreateEntryGroupRequest', +'CreateEntryRequest', +'CreatePolicyTagRequest', +'CreateTagRequest', +'CreateTagTemplateFieldRequest', +'CreateTagTemplateRequest', +'CreateTaxonomyRequest', +'DataCatalogClient', +'DeleteEntryGroupRequest', +'DeleteEntryRequest', +'DeletePolicyTagRequest', +'DeleteTagRequest', +'DeleteTagTemplateFieldRequest', +'DeleteTagTemplateRequest', +'DeleteTaxonomyRequest', +'Entry', +'EntryGroup', +'EntryType', +'ExportTaxonomiesRequest', +'ExportTaxonomiesResponse', +'FieldType', +'GcsFileSpec', +'GcsFilesetSpec', +'GetEntryGroupRequest', +'GetEntryRequest', +'GetPolicyTagRequest', +'GetTagTemplateRequest', +'GetTaxonomyRequest', +'ImportTaxonomiesRequest', +'ImportTaxonomiesResponse', +'InlineSource', +'IntegratedSystem', +'ListEntriesRequest', +'ListEntriesResponse', +'ListEntryGroupsRequest', +'ListEntryGroupsResponse', +'ListPolicyTagsRequest', +'ListPolicyTagsResponse', +'ListTagsRequest', +'ListTagsResponse', +'ListTaxonomiesRequest', +'ListTaxonomiesResponse', +'LookupEntryRequest', +'PolicyTag', +'PolicyTagManagerClient', +'PolicyTagManagerSerializationClient', +'RenameTagTemplateFieldRequest', +'Schema', +'SearchCatalogRequest', +'SearchCatalogResponse', +'SearchCatalogResult', +'SearchResultType', +'SerializedPolicyTag', +'SerializedTaxonomy', +'SystemTimestamps', +'TableSourceType', +'TableSpec', +'Tag', +'TagField', +'TagTemplate', +'TagTemplateField', +'Taxonomy', +'UpdateEntryGroupRequest', +'UpdateEntryRequest', +'UpdatePolicyTagRequest', +'UpdateTagRequest', +'UpdateTagTemplateFieldRequest', +'UpdateTagTemplateRequest', +'UpdateTaxonomyRequest', +'ViewSpec', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..39950163 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json @@ -0,0 +1,471 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.datacatalog_v1beta1", + "protoPackage": "google.cloud.datacatalog.v1beta1", + "schema": "1.0", + "services": { + "DataCatalog": { + "clients": { + "grpc": { + "libraryClient": "DataCatalogClient", + "rpcs": { + "CreateEntry": { + "methods": [ + "create_entry" + ] + }, + "CreateEntryGroup": { + "methods": [ + "create_entry_group" + ] + }, + "CreateTag": { + "methods": [ + "create_tag" + ] + }, + "CreateTagTemplate": { + "methods": [ + "create_tag_template" + ] + }, + "CreateTagTemplateField": { + "methods": [ + "create_tag_template_field" + ] + }, + "DeleteEntry": { + "methods": [ + "delete_entry" + ] + }, + "DeleteEntryGroup": { + "methods": [ + "delete_entry_group" + ] + }, + "DeleteTag": { + "methods": [ + "delete_tag" + ] + }, + "DeleteTagTemplate": { + "methods": [ + "delete_tag_template" + ] + }, + "DeleteTagTemplateField": { + "methods": [ + "delete_tag_template_field" + ] + }, + "GetEntry": { + "methods": [ + "get_entry" + ] + }, + "GetEntryGroup": { + "methods": [ + "get_entry_group" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagTemplate": { + "methods": [ + "get_tag_template" + ] + }, + "ListEntries": { + "methods": [ + "list_entries" + ] + }, + "ListEntryGroups": { + "methods": [ + "list_entry_groups" + ] + }, + "ListTags": { + "methods": [ + "list_tags" + ] + }, + "LookupEntry": { + "methods": [ + "lookup_entry" + ] + }, + "RenameTagTemplateField": { + "methods": [ + "rename_tag_template_field" + ] + }, + "SearchCatalog": { + "methods": [ + "search_catalog" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEntry": { + "methods": [ + "update_entry" + ] + }, + "UpdateEntryGroup": { + "methods": [ + "update_entry_group" + ] + }, + "UpdateTag": { + "methods": [ + "update_tag" + ] + }, + "UpdateTagTemplate": { + "methods": [ + "update_tag_template" + ] + }, + "UpdateTagTemplateField": { + "methods": [ + "update_tag_template_field" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataCatalogAsyncClient", + "rpcs": { + "CreateEntry": { + "methods": [ + "create_entry" + ] + }, + "CreateEntryGroup": { + "methods": [ + "create_entry_group" + ] + }, + "CreateTag": { + "methods": [ + "create_tag" + ] + }, + "CreateTagTemplate": { + "methods": [ + "create_tag_template" + ] + }, + "CreateTagTemplateField": { + "methods": [ + "create_tag_template_field" + ] + }, + "DeleteEntry": { + "methods": [ + "delete_entry" + ] + }, + "DeleteEntryGroup": { + "methods": [ + "delete_entry_group" + ] + }, + "DeleteTag": { + "methods": [ + "delete_tag" + ] + }, + "DeleteTagTemplate": { + "methods": [ + "delete_tag_template" + ] + }, + "DeleteTagTemplateField": { + "methods": [ + "delete_tag_template_field" + ] + }, + "GetEntry": { + "methods": [ + "get_entry" + ] + }, + "GetEntryGroup": { + "methods": [ + "get_entry_group" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagTemplate": { + "methods": [ + "get_tag_template" + ] + }, + "ListEntries": { + "methods": [ + "list_entries" + ] + }, + "ListEntryGroups": { + "methods": [ + "list_entry_groups" + ] + }, + "ListTags": { + "methods": [ + "list_tags" + ] + }, + "LookupEntry": { + "methods": [ + "lookup_entry" + ] + }, + "RenameTagTemplateField": { + "methods": [ + "rename_tag_template_field" + ] + }, + "SearchCatalog": { + "methods": [ + "search_catalog" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateEntry": { + "methods": [ + "update_entry" + ] + }, + "UpdateEntryGroup": { + "methods": [ + "update_entry_group" + ] + }, + "UpdateTag": { + "methods": [ + "update_tag" + ] + }, + "UpdateTagTemplate": { + "methods": [ + "update_tag_template" + ] + }, + "UpdateTagTemplateField": { + "methods": [ + "update_tag_template_field" + ] + } + } + } + } + }, + "PolicyTagManager": { + "clients": { + "grpc": { + "libraryClient": "PolicyTagManagerClient", + "rpcs": { + "CreatePolicyTag": { + "methods": [ + "create_policy_tag" + ] + }, + "CreateTaxonomy": { + "methods": [ + "create_taxonomy" + ] + }, + "DeletePolicyTag": { + "methods": [ + "delete_policy_tag" + ] + }, + "DeleteTaxonomy": { + "methods": [ + "delete_taxonomy" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetPolicyTag": { + "methods": [ + "get_policy_tag" + ] + }, + "GetTaxonomy": { + "methods": [ + "get_taxonomy" + ] + }, + "ListPolicyTags": { + "methods": [ + "list_policy_tags" + ] + }, + "ListTaxonomies": { + "methods": [ + "list_taxonomies" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdatePolicyTag": { + "methods": [ + "update_policy_tag" + ] + }, + "UpdateTaxonomy": { + "methods": [ + "update_taxonomy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyTagManagerAsyncClient", + "rpcs": { + "CreatePolicyTag": { + "methods": [ + "create_policy_tag" + ] + }, + "CreateTaxonomy": { + "methods": [ + "create_taxonomy" + ] + }, + "DeletePolicyTag": { + "methods": [ + "delete_policy_tag" + ] + }, + "DeleteTaxonomy": { + "methods": [ + "delete_taxonomy" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetPolicyTag": { + "methods": [ + "get_policy_tag" + ] + }, + "GetTaxonomy": { + "methods": [ + "get_taxonomy" + ] + }, + "ListPolicyTags": { + "methods": [ + "list_policy_tags" + ] + }, + "ListTaxonomies": { + "methods": [ + "list_taxonomies" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdatePolicyTag": { + "methods": [ + "update_policy_tag" + ] + }, + "UpdateTaxonomy": { + "methods": [ + "update_taxonomy" + ] + } + } + } + } + }, + "PolicyTagManagerSerialization": { + "clients": { + "grpc": { + "libraryClient": "PolicyTagManagerSerializationClient", + "rpcs": { + "ExportTaxonomies": { + "methods": [ + "export_taxonomies" + ] + }, + "ImportTaxonomies": { + "methods": [ + "import_taxonomies" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyTagManagerSerializationAsyncClient", + "rpcs": { + "ExportTaxonomies": { + "methods": [ + "export_taxonomies" + ] + }, + "ImportTaxonomies": { + "methods": [ + "import_taxonomies" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed new file mode 100644 index 00000000..bb4088a3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/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/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py new file mode 100644 index 00000000..b45be1eb --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__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 DataCatalogClient +from .async_client import DataCatalogAsyncClient + +__all__ = ( + 'DataCatalogClient', + 'DataCatalogAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py new file mode 100644 index 00000000..bd522cea --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py @@ -0,0 +1,2878 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers +from google.cloud.datacatalog_v1beta1.types import common +from google.cloud.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1beta1.types import schema +from google.cloud.datacatalog_v1beta1.types import search +from google.cloud.datacatalog_v1beta1.types import table_spec +from google.cloud.datacatalog_v1beta1.types import tags +from google.cloud.datacatalog_v1beta1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport +from .client import DataCatalogClient + + +class DataCatalogAsyncClient: + """Data Catalog API service allows clients to discover, + understand, and manage their data. + """ + + _client: DataCatalogClient + + DEFAULT_ENDPOINT = DataCatalogClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataCatalogClient.DEFAULT_MTLS_ENDPOINT + + entry_path = staticmethod(DataCatalogClient.entry_path) + parse_entry_path = staticmethod(DataCatalogClient.parse_entry_path) + entry_group_path = staticmethod(DataCatalogClient.entry_group_path) + parse_entry_group_path = staticmethod(DataCatalogClient.parse_entry_group_path) + tag_path = staticmethod(DataCatalogClient.tag_path) + parse_tag_path = staticmethod(DataCatalogClient.parse_tag_path) + tag_template_path = staticmethod(DataCatalogClient.tag_template_path) + parse_tag_template_path = staticmethod(DataCatalogClient.parse_tag_template_path) + tag_template_field_path = staticmethod(DataCatalogClient.tag_template_field_path) + parse_tag_template_field_path = staticmethod(DataCatalogClient.parse_tag_template_field_path) + common_billing_account_path = staticmethod(DataCatalogClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataCatalogClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataCatalogClient.common_folder_path) + parse_common_folder_path = staticmethod(DataCatalogClient.parse_common_folder_path) + common_organization_path = staticmethod(DataCatalogClient.common_organization_path) + parse_common_organization_path = staticmethod(DataCatalogClient.parse_common_organization_path) + common_project_path = staticmethod(DataCatalogClient.common_project_path) + parse_common_project_path = staticmethod(DataCatalogClient.parse_common_project_path) + common_location_path = staticmethod(DataCatalogClient.common_location_path) + parse_common_location_path = staticmethod(DataCatalogClient.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: + DataCatalogAsyncClient: The constructed client. + """ + return DataCatalogClient.from_service_account_info.__func__(DataCatalogAsyncClient, 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: + DataCatalogAsyncClient: The constructed client. + """ + return DataCatalogClient.from_service_account_file.__func__(DataCatalogAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DataCatalogTransport: + """Returns the transport used by the client instance. + + Returns: + DataCatalogTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataCatalogClient).get_transport_class, type(DataCatalogClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DataCatalogTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data catalog 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, ~.DataCatalogTransport]): 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 = DataCatalogClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search_catalog(self, + request: Union[datacatalog.SearchCatalogRequest, dict] = None, + *, + scope: datacatalog.SearchCatalogRequest.Scope = None, + query: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchCatalogAsyncPager: + r"""Searches Data Catalog for multiple resources like entries, tags + that match a query. + + This is a custom method + (https://cloud.google.com/apis/design/custom_methods) and does + not return the complete resource, only the resource identifier + and high level fields. Clients can subsequentally call ``Get`` + methods. + + Note that Data Catalog search queries do not guarantee full + recall. Query results that match your query may not be returned, + even in subsequent result pages. Also note that results returned + (and not returned) can vary across repeated search queries. + + See `Data Catalog Search + Syntax `__ + for more information. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest, dict]): + The request object. Request message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + scope (:class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope`): + Required. The scope of this search request. A ``scope`` + that has empty ``include_org_ids``, + ``include_project_ids`` AND false + ``include_gcp_public_datasets`` is considered invalid. + Data Catalog will return an error in such a case. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Required. The query string in search query syntax. The + query must be non-empty. + + Query strings can be simple as "x" or more qualified as: + + - name:x + - column:x + - description:y + + Note: Query tokens need to have a minimum of 3 + characters for substring matching to work correctly. See + `Data Catalog Search + Syntax `__ + for more information. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.services.data_catalog.pagers.SearchCatalogAsyncPager: + Response message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + + 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([scope, query]) + if request is 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 = datacatalog.SearchCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_catalog, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.SearchCatalogAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entry_group(self, + request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, + *, + parent: str = None, + entry_group_id: str = None, + entry_group: datacatalog.EntryGroup = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""A maximum of 10,000 entry groups may be created per organization + across all locations. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryGroupRequest, dict]): + The request object. Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. + parent (:class:`str`): + Required. The name of the project this entry group is + in. Example: + + - projects/{project_id}/locations/{location} + + Note that this EntryGroup and its child resources may + not actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group_id (:class:`str`): + Required. The id of the entry group + to create. The id must begin with a + letter or underscore, contain only + English letters, numbers and + underscores, and be at most 64 + characters. + + This corresponds to the ``entry_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group (:class:`google.cloud.datacatalog_v1beta1.types.EntryGroup`): + The entry group to create. Defaults + to an empty entry group. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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, entry_group_id, entry_group]) + if request is 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 = datacatalog.CreateEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_group_id is not None: + request.entry_group_id = entry_group_id + if entry_group is not None: + request.entry_group = entry_group + + # 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_entry_group, + default_timeout=None, + client_info=DEFAULT_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_entry_group(self, + request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, + *, + entry_group: datacatalog.EntryGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Updates an EntryGroup. The user should enable the Data Catalog + API in the project identified by the ``entry_group.name`` + parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryGroupRequest, dict]): + The request object. Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. + entry_group (:class:`google.cloud.datacatalog_v1beta1.types.EntryGroup`): + Required. The updated entry group. + "name" field must be set. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update on the entry + group. If absent or empty, all + modifiable fields are updated. + + 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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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([entry_group, 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 = datacatalog.UpdateEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry_group is not None: + request.entry_group = entry_group + 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_entry_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry_group.name", request.entry_group.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_entry_group(self, + request: Union[datacatalog.GetEntryGroupRequest, dict] = None, + *, + name: str = None, + read_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Gets an EntryGroup. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryGroupRequest, dict]): + The request object. Request message for + [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. + name (:class:`str`): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + read_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to return. If not set or + empty, all fields are returned. + + This corresponds to the ``read_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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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, read_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 = datacatalog.GetEntryGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if read_mask is not None: + request.read_mask = read_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.get_entry_group, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entry_group(self, + request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an EntryGroup. Only entry groups that do not contain + entries can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryGroupRequest, dict]): + The request object. Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. + name (:class:`str`): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_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 = datacatalog.DeleteEntryGroupRequest(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_entry_group, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_entry_groups(self, + request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntryGroupsAsyncPager: + r"""Lists entry groups. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListEntryGroupsRequest, dict]): + The request object. Request message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + parent (:class:`str`): + Required. The name of the location that contains the + entry groups, which can be provided in URL format. + Example: + + - projects/{project_id}/locations/{location} + + 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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntryGroupsAsyncPager: + Response message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + + 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 = datacatalog.ListEntryGroupsRequest(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_entry_groups, + default_timeout=None, + client_info=DEFAULT_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.ListEntryGroupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entry(self, + request: Union[datacatalog.CreateEntryRequest, dict] = None, + *, + parent: str = None, + entry_id: str = None, + entry: datacatalog.Entry = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Creates an entry. Only entries of 'FILESET' type or + user-specified type can be created. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + A maximum of 100,000 entries may be created per entry group. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryRequest, dict]): + The request object. Request message for + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. + parent (:class:`str`): + Required. The name of the entry group this entry is in. + Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + + Note that this Entry and its child resources may not + actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_id (:class:`str`): + Required. The id of the entry to + create. + + This corresponds to the ``entry_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry (:class:`google.cloud.datacatalog_v1beta1.types.Entry`): + Required. The entry to create. + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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, entry_id, entry]) + if request is 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 = datacatalog.CreateEntryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_id is not None: + request.entry_id = entry_id + if entry is not None: + request.entry = entry + + # 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_entry, + default_timeout=None, + client_info=DEFAULT_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_entry(self, + request: Union[datacatalog.UpdateEntryRequest, dict] = None, + *, + entry: datacatalog.Entry = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Updates an existing entry. Users should enable the Data Catalog + API in the project identified by the ``entry.name`` parameter + (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryRequest, dict]): + The request object. Request message for + [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. + entry (:class:`google.cloud.datacatalog_v1beta1.types.Entry`): + Required. The updated entry. The + "name" field must be set. + + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update on the entry. If absent or empty, + all modifiable fields are updated. + + The following fields are modifiable: + + - For entries with type ``DATA_STREAM``: + + - ``schema`` + + - For entries with type ``FILESET`` + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + - For entries with ``user_specified_type`` + + - ``schema`` + - ``display_name`` + - ``description`` + - user_specified_type + - user_specified_system + - linked_resource + - source_system_timestamps + + 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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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([entry, 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 = datacatalog.UpdateEntryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry is not None: + request.entry = entry + 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_entry, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry.name", request.entry.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entry(self, + request: Union[datacatalog.DeleteEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing entry. Only entries created through + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] + method can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryRequest, dict]): + The request object. Request message for + [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. + name (:class:`str`): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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 = datacatalog.DeleteEntryRequest(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_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_entry(self, + request: Union[datacatalog.GetEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryRequest, dict]): + The request object. Request message for + [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. + name (:class:`str`): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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 = datacatalog.GetEntryRequest(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_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def lookup_entry(self, + request: Union[datacatalog.LookupEntryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Get an entry by target resource name. This method + allows clients to use the resource name from the source + Google Cloud Platform service to get the Data Catalog + Entry. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.LookupEntryRequest, dict]): + The request object. Request message for + [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # Create or coerce a protobuf request object. + request = datacatalog.LookupEntryRequest(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.lookup_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_entries(self, + request: Union[datacatalog.ListEntriesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntriesAsyncPager: + r"""Lists entries. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListEntriesRequest, dict]): + The request object. Request message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + parent (:class:`str`): + Required. The name of the entry group that contains the + entries, which can be provided in URL format. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntriesAsyncPager: + Response message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + + 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 = datacatalog.ListEntriesRequest(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_entries, + default_timeout=None, + client_info=DEFAULT_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.ListEntriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tag_template(self, + request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, + *, + parent: str = None, + tag_template_id: str = None, + tag_template: tags.TagTemplate = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Creates a tag template. The user should enable the Data Catalog + API in the project identified by the ``parent`` parameter (see + `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateRequest, dict]): + The request object. Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. + parent (:class:`str`): + Required. The name of the project and the template + location + [region](https://cloud.google.com/data-catalog/docs/concepts/regions. + + Example: + + - projects/{project_id}/locations/us-central1 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_id (:class:`str`): + Required. The id of the tag template + to create. + + This corresponds to the ``tag_template_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplate`): + Required. The tag template to create. + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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, tag_template_id, tag_template]) + if request is 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 = datacatalog.CreateTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_id is not None: + request.tag_template_id = tag_template_id + if tag_template is not None: + request.tag_template = tag_template + + # 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_tag_template, + default_timeout=None, + client_info=DEFAULT_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_tag_template(self, + request: Union[datacatalog.GetTagTemplateRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Gets a tag template. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetTagTemplateRequest, dict]): + The request object. Request message for + [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. + name (:class:`str`): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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 = datacatalog.GetTagTemplateRequest(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_tag_template, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_tag_template(self, + request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, + *, + tag_template: tags.TagTemplate = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Updates a tag template. This method cannot be used to update the + fields of a template. The tag template fields are represented as + separate resources and should be updated using their own + create/update/delete methods. Users should enable the Data + Catalog API in the project identified by the + ``tag_template.name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateRequest, dict]): + The request object. Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. + tag_template (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplate`): + Required. The template to update. The + "name" field must be set. + + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The field mask specifies the parts of the template to + overwrite. + + Allowed fields: + + - ``display_name`` + + If absent or empty, all of the allowed fields above will + be updated. + + 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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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([tag_template, 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 = datacatalog.UpdateTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_template is not None: + request.tag_template = tag_template + 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_tag_template, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_template.name", request.tag_template.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tag_template(self, + request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag template and all tags using the template. Users + should enable the Data Catalog API in the project identified by + the ``name`` parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateRequest, dict]): + The request object. Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. + name (:class:`str`): + Required. The name of the tag template to delete. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of any possible + tags using this template. ``force = false`` will be + supported in the future. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 = datacatalog.DeleteTagTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # 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_tag_template, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_tag_template_field(self, + request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, + *, + parent: str = None, + tag_template_field_id: str = None, + tag_template_field: tags.TagTemplateField = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Creates a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``parent`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateFieldRequest, dict]): + The request object. Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. + parent (:class:`str`): + Required. The name of the project and the template + location + `region `__. + + Example: + + - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field_id (:class:`str`): + Required. The ID of the tag template field to create. + Field ids can contain letters (both uppercase and + lowercase), numbers (0-9), underscores (_) and dashes + (-). Field IDs must be at least 1 character long and at + most 128 characters long. Field IDs must also be unique + within their template. + + This corresponds to the ``tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplateField`): + Required. The tag template field to + create. + + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field_id, tag_template_field]) + if request is 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 = datacatalog.CreateTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_field_id is not None: + request.tag_template_field_id = tag_template_field_id + if tag_template_field is not None: + request.tag_template_field = tag_template_field + + # 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_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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_tag_template_field(self, + request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + tag_template_field: tags.TagTemplateField = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Updates a field in a tag template. This method cannot be used to + update the field type. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateFieldRequest, dict]): + The request object. Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. + name (:class:`str`): + Required. The name of the tag template field. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplateField`): + Required. The template to update. + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The field mask specifies the parts of the + template to be updated. Allowed fields: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If ``update_mask`` is not set or empty, all of the + allowed fields above will be updated. + + When updating an enum type, the provided values will be + merged with the existing values. Therefore, enum values + can only be added, existing enum values cannot be + deleted nor renamed. Updating a template field from + optional to required is NOT allowed. + + 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.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field, 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 = datacatalog.UpdateTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if tag_template_field is not None: + request.tag_template_field = tag_template_field + 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_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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 rename_tag_template_field(self, + request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + new_tag_template_field_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``name`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.RenameTagTemplateFieldRequest, dict]): + The request object. Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. + name (:class:`str`): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_tag_template_field_id (:class:`str`): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + + This corresponds to the ``new_tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_tag_template_field_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = datacatalog.RenameTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_tag_template_field_id is not None: + request.new_tag_template_field_id = new_tag_template_field_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.rename_tag_template_field, + default_timeout=None, + client_info=DEFAULT_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_tag_template_field(self, + request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a field in a tag template and all uses of that field. + Users should enable the Data Catalog API in the project + identified by the ``name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateFieldRequest, dict]): + The request object. Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. + name (:class:`str`): + Required. The name of the tag template field to delete. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of this field from + any tags using this field. ``force = false`` will be + supported in the future. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 = datacatalog.DeleteTagTemplateFieldRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # 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_tag_template_field, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_tag(self, + request: Union[datacatalog.CreateTagRequest, dict] = None, + *, + parent: str = None, + tag: tags.Tag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Creates a tag on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The + project identified by the ``parent`` parameter for the + `tag `__ + and the `tag + template `__ + used to create the tag must be from the same organization. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagRequest, dict]): + The request object. Request message for + [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. + parent (:class:`str`): + Required. The name of the resource to attach this tag + to. Tags can be attached to Entries. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + + Note that this Tag and its child resources may not + actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag (:class:`google.cloud.datacatalog_v1beta1.types.Tag`): + Required. The tag to create. + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Tag: + Tags are used to attach custom metadata to Data Catalog resources. Tags + conform to the specifications within their tag + template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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, tag]) + if request is 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 = datacatalog.CreateTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag is not None: + request.tag = tag + + # 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_tag, + default_timeout=None, + client_info=DEFAULT_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_tag(self, + request: Union[datacatalog.UpdateTagRequest, dict] = None, + *, + tag: tags.Tag = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Updates an existing tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagRequest, dict]): + The request object. Request message for + [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. + tag (:class:`google.cloud.datacatalog_v1beta1.types.Tag`): + Required. The updated tag. The "name" + field must be set. + + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update on the Tag. If absent or empty, all + modifiable fields are updated. Currently the only + modifiable field is the field ``fields``. + + 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.datacatalog_v1beta1.types.Tag: + Tags are used to attach custom metadata to Data Catalog resources. Tags + conform to the specifications within their tag + template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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([tag, 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 = datacatalog.UpdateTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag is not None: + request.tag = tag + 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_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag.name", request.tag.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tag(self, + request: Union[datacatalog.DeleteTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagRequest, dict]): + The request object. Request message for + [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. + name (:class:`str`): + Required. The name of the tag to delete. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_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 = datacatalog.DeleteTagRequest(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_tag, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_tags(self, + request: Union[datacatalog.ListTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTagsAsyncPager: + r"""Lists the tags on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListTagsRequest, dict]): + The request object. Request message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + parent (:class:`str`): + Required. The name of the Data Catalog resource to list + the tags of. The resource could be an + [Entry][google.cloud.datacatalog.v1beta1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. + + Examples: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.services.data_catalog.pagers.ListTagsAsyncPager: + Response message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + + 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 = datacatalog.ListTagsRequest(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_tags, + 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=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy for a resource. Replaces any + existing policy. Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entries.setIamPolicy`` to set policies on + entries. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. A ``NOT_FOUND`` + error is returned if the resource does not exist. An empty + policy is returned if the resource exists but does not have a + policy set on it. + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entries.getIamPolicy`` to get policies on + entries. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # 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_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the caller's permissions on a resource. If the resource + does not exist, an empty set of permissions is returned (We + don't return a ``NOT_FOUND`` error). + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + A caller is not required to have Google IAM permission to make + this request. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataCatalogAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py new file mode 100644 index 00000000..9adf67c4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py @@ -0,0 +1,3039 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers +from google.cloud.datacatalog_v1beta1.types import common +from google.cloud.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1beta1.types import schema +from google.cloud.datacatalog_v1beta1.types import search +from google.cloud.datacatalog_v1beta1.types import table_spec +from google.cloud.datacatalog_v1beta1.types import tags +from google.cloud.datacatalog_v1beta1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataCatalogGrpcTransport +from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport + + +class DataCatalogClientMeta(type): + """Metaclass for the DataCatalog 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[DataCatalogTransport]] + _transport_registry["grpc"] = DataCatalogGrpcTransport + _transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DataCatalogTransport]: + """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 DataCatalogClient(metaclass=DataCatalogClientMeta): + """Data Catalog API service allows clients to discover, + understand, and manage their data. + """ + + @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 = "datacatalog.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: + DataCatalogClient: 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: + DataCatalogClient: 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) -> DataCatalogTransport: + """Returns the transport used by the client instance. + + Returns: + DataCatalogTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entry_path(project: str,location: str,entry_group: str,entry: str,) -> str: + """Returns a fully-qualified entry string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) + + @staticmethod + def parse_entry_path(path: str) -> Dict[str,str]: + """Parses a entry path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def entry_group_path(project: str,location: str,entry_group: str,) -> str: + """Returns a fully-qualified entry_group string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) + + @staticmethod + def parse_entry_group_path(path: str) -> Dict[str,str]: + """Parses a entry_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_path(project: str,location: str,entry_group: str,entry: str,tag: str,) -> str: + """Returns a fully-qualified tag string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) + + @staticmethod + def parse_tag_path(path: str) -> Dict[str,str]: + """Parses a tag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)/tags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_template_path(project: str,location: str,tag_template: str,) -> str: + """Returns a fully-qualified tag_template string.""" + return "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) + + @staticmethod + def parse_tag_template_path(path: str) -> Dict[str,str]: + """Parses a tag_template path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def tag_template_field_path(project: str,location: str,tag_template: str,field: str,) -> str: + """Returns a fully-qualified tag_template_field string.""" + return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) + + @staticmethod + def parse_tag_template_field_path(path: str) -> Dict[str,str]: + """Parses a tag_template_field path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?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, DataCatalogTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data catalog 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, DataCatalogTransport]): 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, DataCatalogTransport): + # transport is a DataCatalogTransport 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=True, + ) + + def search_catalog(self, + request: Union[datacatalog.SearchCatalogRequest, dict] = None, + *, + scope: datacatalog.SearchCatalogRequest.Scope = None, + query: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchCatalogPager: + r"""Searches Data Catalog for multiple resources like entries, tags + that match a query. + + This is a custom method + (https://cloud.google.com/apis/design/custom_methods) and does + not return the complete resource, only the resource identifier + and high level fields. Clients can subsequentally call ``Get`` + methods. + + Note that Data Catalog search queries do not guarantee full + recall. Query results that match your query may not be returned, + even in subsequent result pages. Also note that results returned + (and not returned) can vary across repeated search queries. + + See `Data Catalog Search + Syntax `__ + for more information. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest, dict]): + The request object. Request message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + scope (google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope): + Required. The scope of this search request. A ``scope`` + that has empty ``include_org_ids``, + ``include_project_ids`` AND false + ``include_gcp_public_datasets`` is considered invalid. + Data Catalog will return an error in such a case. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Required. The query string in search query syntax. The + query must be non-empty. + + Query strings can be simple as "x" or more qualified as: + + - name:x + - column:x + - description:y + + Note: Query tokens need to have a minimum of 3 + characters for substring matching to work correctly. See + `Data Catalog Search + Syntax `__ + for more information. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.services.data_catalog.pagers.SearchCatalogPager: + Response message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + + 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([scope, query]) + if request is 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 datacatalog.SearchCatalogRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.SearchCatalogRequest): + request = datacatalog.SearchCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_catalog] + + # 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.SearchCatalogPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entry_group(self, + request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, + *, + parent: str = None, + entry_group_id: str = None, + entry_group: datacatalog.EntryGroup = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""A maximum of 10,000 entry groups may be created per organization + across all locations. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryGroupRequest, dict]): + The request object. Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. + parent (str): + Required. The name of the project this entry group is + in. Example: + + - projects/{project_id}/locations/{location} + + Note that this EntryGroup and its child resources may + not actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group_id (str): + Required. The id of the entry group + to create. The id must begin with a + letter or underscore, contain only + English letters, numbers and + underscores, and be at most 64 + characters. + + This corresponds to the ``entry_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): + The entry group to create. Defaults + to an empty entry group. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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, entry_group_id, entry_group]) + if request is 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 datacatalog.CreateEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateEntryGroupRequest): + request = datacatalog.CreateEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_group_id is not None: + request.entry_group_id = entry_group_id + if entry_group is not None: + request.entry_group = entry_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entry_group] + + # 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_entry_group(self, + request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, + *, + entry_group: datacatalog.EntryGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Updates an EntryGroup. The user should enable the Data Catalog + API in the project identified by the ``entry_group.name`` + parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryGroupRequest, dict]): + The request object. Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. + entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): + Required. The updated entry group. + "name" field must be set. + + This corresponds to the ``entry_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the entry + group. If absent or empty, all + modifiable fields are updated. + + 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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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([entry_group, 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 datacatalog.UpdateEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateEntryGroupRequest): + request = datacatalog.UpdateEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry_group is not None: + request.entry_group = entry_group + 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_entry_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry_group.name", request.entry_group.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_entry_group(self, + request: Union[datacatalog.GetEntryGroupRequest, dict] = None, + *, + name: str = None, + read_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.EntryGroup: + r"""Gets an EntryGroup. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryGroupRequest, dict]): + The request object. Request message for + [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. + name (str): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return. If not set or + empty, all fields are returned. + + This corresponds to the ``read_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.datacatalog_v1beta1.types.EntryGroup: + EntryGroup Metadata. + An EntryGroup resource represents a logical grouping + of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] + resources. + + """ + # 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, read_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 datacatalog.GetEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetEntryGroupRequest): + request = datacatalog.GetEntryGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if read_mask is not None: + request.read_mask = read_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_entry_group] + + # Certain fields should be 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_entry_group(self, + request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an EntryGroup. Only entry groups that do not contain + entries can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryGroupRequest, dict]): + The request object. Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. + name (str): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_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 datacatalog.DeleteEntryGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteEntryGroupRequest): + request = datacatalog.DeleteEntryGroupRequest(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_entry_group] + + # Certain fields should be 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_entry_groups(self, + request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntryGroupsPager: + r"""Lists entry groups. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListEntryGroupsRequest, dict]): + The request object. Request message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + parent (str): + Required. The name of the location that contains the + entry groups, which can be provided in URL format. + Example: + + - projects/{project_id}/locations/{location} + + 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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntryGroupsPager: + Response message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + + 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 datacatalog.ListEntryGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListEntryGroupsRequest): + request = datacatalog.ListEntryGroupsRequest(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_entry_groups] + + # 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.ListEntryGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entry(self, + request: Union[datacatalog.CreateEntryRequest, dict] = None, + *, + parent: str = None, + entry_id: str = None, + entry: datacatalog.Entry = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Creates an entry. Only entries of 'FILESET' type or + user-specified type can be created. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + A maximum of 100,000 entries may be created per entry group. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryRequest, dict]): + The request object. Request message for + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. + parent (str): + Required. The name of the entry group this entry is in. + Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + + Note that this Entry and its child resources may not + actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry_id (str): + Required. The id of the entry to + create. + + This corresponds to the ``entry_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entry (google.cloud.datacatalog_v1beta1.types.Entry): + Required. The entry to create. + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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, entry_id, entry]) + if request is 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 datacatalog.CreateEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateEntryRequest): + request = datacatalog.CreateEntryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entry_id is not None: + request.entry_id = entry_id + if entry is not None: + request.entry = entry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entry] + + # 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_entry(self, + request: Union[datacatalog.UpdateEntryRequest, dict] = None, + *, + entry: datacatalog.Entry = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Updates an existing entry. Users should enable the Data Catalog + API in the project identified by the ``entry.name`` parameter + (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryRequest, dict]): + The request object. Request message for + [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. + entry (google.cloud.datacatalog_v1beta1.types.Entry): + Required. The updated entry. The + "name" field must be set. + + This corresponds to the ``entry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the entry. If absent or empty, + all modifiable fields are updated. + + The following fields are modifiable: + + - For entries with type ``DATA_STREAM``: + + - ``schema`` + + - For entries with type ``FILESET`` + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + - For entries with ``user_specified_type`` + + - ``schema`` + - ``display_name`` + - ``description`` + - user_specified_type + - user_specified_system + - linked_resource + - source_system_timestamps + + 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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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([entry, 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 datacatalog.UpdateEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateEntryRequest): + request = datacatalog.UpdateEntryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entry is not None: + request.entry = entry + 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_entry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entry.name", request.entry.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entry(self, + request: Union[datacatalog.DeleteEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing entry. Only entries created through + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] + method can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryRequest, dict]): + The request object. Request message for + [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. + name (str): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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 datacatalog.DeleteEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteEntryRequest): + request = datacatalog.DeleteEntryRequest(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_entry] + + # Certain fields should be 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_entry(self, + request: Union[datacatalog.GetEntryRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Gets an entry. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryRequest, dict]): + The request object. Request message for + [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. + name (str): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # 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 datacatalog.GetEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetEntryRequest): + request = datacatalog.GetEntryRequest(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_entry] + + # Certain fields should be 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 lookup_entry(self, + request: Union[datacatalog.LookupEntryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> datacatalog.Entry: + r"""Get an entry by target resource name. This method + allows clients to use the resource name from the source + Google Cloud Platform service to get the Data Catalog + Entry. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.LookupEntryRequest, dict]): + The request object. Request message for + [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Entry: + Entry Metadata. + A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery + dataset or a Pub/Sub topic), or outside of Google + Cloud Platform. Clients can use the linked_resource + field in the Entry resource to refer to the original + resource ID of the source system. + + An Entry resource contains resource details, such as + its schema. An Entry can also be used to attach + flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a datacatalog.LookupEntryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.LookupEntryRequest): + request = datacatalog.LookupEntryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lookup_entry] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_entries(self, + request: Union[datacatalog.ListEntriesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntriesPager: + r"""Lists entries. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListEntriesRequest, dict]): + The request object. Request message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + parent (str): + Required. The name of the entry group that contains the + entries, which can be provided in URL format. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntriesPager: + Response message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + + 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 datacatalog.ListEntriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListEntriesRequest): + request = datacatalog.ListEntriesRequest(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_entries] + + # 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.ListEntriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tag_template(self, + request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, + *, + parent: str = None, + tag_template_id: str = None, + tag_template: tags.TagTemplate = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Creates a tag template. The user should enable the Data Catalog + API in the project identified by the ``parent`` parameter (see + `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateRequest, dict]): + The request object. Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. + parent (str): + Required. The name of the project and the template + location + [region](https://cloud.google.com/data-catalog/docs/concepts/regions. + + Example: + + - projects/{project_id}/locations/us-central1 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_id (str): + Required. The id of the tag template + to create. + + This corresponds to the ``tag_template_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): + Required. The tag template to create. + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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, tag_template_id, tag_template]) + if request is 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 datacatalog.CreateTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagTemplateRequest): + request = datacatalog.CreateTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_id is not None: + request.tag_template_id = tag_template_id + if tag_template is not None: + request.tag_template = tag_template + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_template] + + # 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_tag_template(self, + request: Union[datacatalog.GetTagTemplateRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Gets a tag template. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetTagTemplateRequest, dict]): + The request object. Request message for + [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. + name (str): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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 datacatalog.GetTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.GetTagTemplateRequest): + request = datacatalog.GetTagTemplateRequest(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_tag_template] + + # Certain fields should be 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 update_tag_template(self, + request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, + *, + tag_template: tags.TagTemplate = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplate: + r"""Updates a tag template. This method cannot be used to update the + fields of a template. The tag template fields are represented as + separate resources and should be updated using their own + create/update/delete methods. Users should enable the Data + Catalog API in the project identified by the + ``tag_template.name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateRequest, dict]): + The request object. Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. + tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): + Required. The template to update. The + "name" field must be set. + + This corresponds to the ``tag_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask specifies the parts of the template to + overwrite. + + Allowed fields: + + - ``display_name`` + + If absent or empty, all of the allowed fields above will + be updated. + + 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.datacatalog_v1beta1.types.TagTemplate: + A tag template defines a tag, which can have one or more typed fields. + The template is used to create and attach the tag to + GCP resources. [Tag template + roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) + provide permissions to create, edit, and use the + template. See, for example, the [TagTemplate + User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) + role, which includes permission to use the tag + template to tag resources. + + """ + # 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([tag_template, 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 datacatalog.UpdateTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagTemplateRequest): + request = datacatalog.UpdateTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_template is not None: + request.tag_template = tag_template + 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_tag_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_template.name", request.tag_template.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tag_template(self, + request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag template and all tags using the template. Users + should enable the Data Catalog API in the project identified by + the ``name`` parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateRequest, dict]): + The request object. Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. + name (str): + Required. The name of the tag template to delete. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of any possible + tags using this template. ``force = false`` will be + supported in the future. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 datacatalog.DeleteTagTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagTemplateRequest): + request = datacatalog.DeleteTagTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_template] + + # Certain fields should be 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 create_tag_template_field(self, + request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, + *, + parent: str = None, + tag_template_field_id: str = None, + tag_template_field: tags.TagTemplateField = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Creates a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``parent`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateFieldRequest, dict]): + The request object. Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. + parent (str): + Required. The name of the project and the template + location + `region `__. + + Example: + + - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field_id (str): + Required. The ID of the tag template field to create. + Field ids can contain letters (both uppercase and + lowercase), numbers (0-9), underscores (_) and dashes + (-). Field IDs must be at least 1 character long and at + most 128 characters long. Field IDs must also be unique + within their template. + + This corresponds to the ``tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): + Required. The tag template field to + create. + + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field_id, tag_template_field]) + if request is 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 datacatalog.CreateTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagTemplateFieldRequest): + request = datacatalog.CreateTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag_template_field_id is not None: + request.tag_template_field_id = tag_template_field_id + if tag_template_field is not None: + request.tag_template_field = tag_template_field + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_template_field] + + # 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_tag_template_field(self, + request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + tag_template_field: tags.TagTemplateField = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Updates a field in a tag template. This method cannot be used to + update the field type. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateFieldRequest, dict]): + The request object. Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. + name (str): + Required. The name of the tag template field. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): + Required. The template to update. + This corresponds to the ``tag_template_field`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The field mask specifies the parts of the + template to be updated. Allowed fields: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If ``update_mask`` is not set or empty, all of the + allowed fields above will be updated. + + When updating an enum type, the provided values will be + merged with the existing values. Therefore, enum values + can only be added, existing enum values cannot be + deleted nor renamed. Updating a template field from + optional to required is NOT allowed. + + 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.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, tag_template_field, 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 datacatalog.UpdateTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagTemplateFieldRequest): + request = datacatalog.UpdateTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if tag_template_field is not None: + request.tag_template_field = tag_template_field + 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_tag_template_field] + + # Certain fields should be 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 rename_tag_template_field(self, + request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + new_tag_template_field_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.TagTemplateField: + r"""Renames a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``name`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.RenameTagTemplateFieldRequest, dict]): + The request object. Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. + name (str): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + new_tag_template_field_id (str): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + + This corresponds to the ``new_tag_template_field_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.datacatalog_v1beta1.types.TagTemplateField: + The template for an individual field + within a tag template. + + """ + # 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, new_tag_template_field_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a datacatalog.RenameTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.RenameTagTemplateFieldRequest): + request = datacatalog.RenameTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if new_tag_template_field_id is not None: + request.new_tag_template_field_id = new_tag_template_field_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field] + + # Certain fields should be 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_tag_template_field(self, + request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, + *, + name: str = None, + force: bool = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a field in a tag template and all uses of that field. + Users should enable the Data Catalog API in the project + identified by the ``name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateFieldRequest, dict]): + The request object. Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. + name (str): + Required. The name of the tag template field to delete. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of this field from + any tags using this field. ``force = false`` will be + supported in the future. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, force]) + if request is 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 datacatalog.DeleteTagTemplateFieldRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagTemplateFieldRequest): + request = datacatalog.DeleteTagTemplateFieldRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_template_field] + + # Certain fields should be 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 create_tag(self, + request: Union[datacatalog.CreateTagRequest, dict] = None, + *, + parent: str = None, + tag: tags.Tag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Creates a tag on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The + project identified by the ``parent`` parameter for the + `tag `__ + and the `tag + template `__ + used to create the tag must be from the same organization. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagRequest, dict]): + The request object. Request message for + [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. + parent (str): + Required. The name of the resource to attach this tag + to. Tags can be attached to Entries. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + + Note that this Tag and its child resources may not + actually be stored in the location in this name. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tag (google.cloud.datacatalog_v1beta1.types.Tag): + Required. The tag to create. + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Tag: + Tags are used to attach custom metadata to Data Catalog resources. Tags + conform to the specifications within their tag + template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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, tag]) + if request is 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 datacatalog.CreateTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.CreateTagRequest): + request = datacatalog.CreateTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tag is not None: + request.tag = tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag] + + # 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_tag(self, + request: Union[datacatalog.UpdateTagRequest, dict] = None, + *, + tag: tags.Tag = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tags.Tag: + r"""Updates an existing tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagRequest, dict]): + The request object. Request message for + [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. + tag (google.cloud.datacatalog_v1beta1.types.Tag): + Required. The updated tag. The "name" + field must be set. + + This corresponds to the ``tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the Tag. If absent or empty, all + modifiable fields are updated. Currently the only + modifiable field is the field ``fields``. + + 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.datacatalog_v1beta1.types.Tag: + Tags are used to attach custom metadata to Data Catalog resources. Tags + conform to the specifications within their tag + template. + + See [Data Catalog + IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) + for information on the permissions needed to create + or view tags. + + """ + # 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([tag, 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 datacatalog.UpdateTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.UpdateTagRequest): + request = datacatalog.UpdateTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag is not None: + request.tag = tag + 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_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag.name", request.tag.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tag(self, + request: Union[datacatalog.DeleteTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagRequest, dict]): + The request object. Request message for + [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. + name (str): + Required. The name of the tag to delete. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_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 datacatalog.DeleteTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.DeleteTagRequest): + request = datacatalog.DeleteTagRequest(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_tag] + + # Certain fields should be 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_tags(self, + request: Union[datacatalog.ListTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTagsPager: + r"""Lists the tags on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListTagsRequest, dict]): + The request object. Request message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + parent (str): + Required. The name of the Data Catalog resource to list + the tags of. The resource could be an + [Entry][google.cloud.datacatalog.v1beta1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. + + Examples: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.services.data_catalog.pagers.ListTagsPager: + Response message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + + 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 datacatalog.ListTagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, datacatalog.ListTagsRequest): + request = datacatalog.ListTagsRequest(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_tags] + + # 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.ListTagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy for a resource. Replaces any + existing policy. Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entries.setIamPolicy`` to set policies on + entries. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + resource: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. A ``NOT_FOUND`` + error is returned if the resource does not exist. An empty + policy is returned if the resource exists but does not have a + policy set on it. + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entries.getIamPolicy`` to get policies on + entries. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # 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([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the caller's permissions on a resource. If the resource + does not exist, an empty set of permissions is returned (We + don't return a ``NOT_FOUND`` error). + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + A caller is not required to have Google IAM permission to make + this request. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DataCatalogClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py new file mode 100644 index 00000000..d53b511a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py @@ -0,0 +1,508 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import search +from google.cloud.datacatalog_v1beta1.types import tags + + +class SearchCatalogPager: + """A pager for iterating through ``search_catalog`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchCatalog`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` + 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[..., datacatalog.SearchCatalogResponse], + request: datacatalog.SearchCatalogRequest, + response: datacatalog.SearchCatalogResponse, + *, + 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.datacatalog_v1beta1.types.SearchCatalogRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse): + 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 = datacatalog.SearchCatalogRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.SearchCatalogResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search.SearchCatalogResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchCatalogAsyncPager: + """A pager for iterating through ``search_catalog`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchCatalog`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` + 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[datacatalog.SearchCatalogResponse]], + request: datacatalog.SearchCatalogRequest, + response: datacatalog.SearchCatalogResponse, + *, + 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.datacatalog_v1beta1.types.SearchCatalogRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse): + 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 = datacatalog.SearchCatalogRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.SearchCatalogResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[search.SearchCatalogResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntryGroupsPager: + """A pager for iterating through ``list_entry_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entry_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntryGroups`` requests and continue to iterate + through the ``entry_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` + 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[..., datacatalog.ListEntryGroupsResponse], + request: datacatalog.ListEntryGroupsRequest, + response: datacatalog.ListEntryGroupsResponse, + *, + 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.datacatalog_v1beta1.types.ListEntryGroupsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse): + 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 = datacatalog.ListEntryGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListEntryGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[datacatalog.EntryGroup]: + for page in self.pages: + yield from page.entry_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntryGroupsAsyncPager: + """A pager for iterating through ``list_entry_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entry_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntryGroups`` requests and continue to iterate + through the ``entry_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` + 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[datacatalog.ListEntryGroupsResponse]], + request: datacatalog.ListEntryGroupsRequest, + response: datacatalog.ListEntryGroupsResponse, + *, + 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.datacatalog_v1beta1.types.ListEntryGroupsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse): + 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 = datacatalog.ListEntryGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListEntryGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[datacatalog.EntryGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.entry_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntriesPager: + """A pager for iterating through ``list_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` + 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[..., datacatalog.ListEntriesResponse], + request: datacatalog.ListEntriesRequest, + response: datacatalog.ListEntriesResponse, + *, + 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.datacatalog_v1beta1.types.ListEntriesRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListEntriesResponse): + 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 = datacatalog.ListEntriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[datacatalog.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntriesAsyncPager: + """A pager for iterating through ``list_entries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntries`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` + 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[datacatalog.ListEntriesResponse]], + request: datacatalog.ListEntriesRequest, + response: datacatalog.ListEntriesResponse, + *, + 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.datacatalog_v1beta1.types.ListEntriesRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListEntriesResponse): + 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 = datacatalog.ListEntriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListEntriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[datacatalog.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagsPager: + """A pager for iterating through ``list_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTags`` requests and continue to iterate + through the ``tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` + 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[..., datacatalog.ListTagsResponse], + request: datacatalog.ListTagsRequest, + response: datacatalog.ListTagsResponse, + *, + 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.datacatalog_v1beta1.types.ListTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListTagsResponse): + 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 = datacatalog.ListTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datacatalog.ListTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tags.Tag]: + for page in self.pages: + yield from page.tags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagsAsyncPager: + """A pager for iterating through ``list_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTags`` requests and continue to iterate + through the ``tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` + 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[datacatalog.ListTagsResponse]], + request: datacatalog.ListTagsRequest, + response: datacatalog.ListTagsResponse, + *, + 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.datacatalog_v1beta1.types.ListTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListTagsResponse): + 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 = datacatalog.ListTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[datacatalog.ListTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[tags.Tag]: + async def async_generator(): + async for page in self.pages: + for response in page.tags: + 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/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py new file mode 100644 index 00000000..f8baae0c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/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 DataCatalogTransport +from .grpc import DataCatalogGrpcTransport +from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]] +_transport_registry['grpc'] = DataCatalogGrpcTransport +_transport_registry['grpc_asyncio'] = DataCatalogGrpcAsyncIOTransport + +__all__ = ( + 'DataCatalogTransport', + 'DataCatalogGrpcTransport', + 'DataCatalogGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py new file mode 100644 index 00000000..6513efdd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py @@ -0,0 +1,584 @@ +# -*- 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 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.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class DataCatalogTransport(abc.ABC): + """Abstract transport class for DataCatalog.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search_catalog: gapic_v1.method.wrap_method( + self.search_catalog, + default_timeout=None, + client_info=client_info, + ), + self.create_entry_group: gapic_v1.method.wrap_method( + self.create_entry_group, + default_timeout=None, + client_info=client_info, + ), + self.update_entry_group: gapic_v1.method.wrap_method( + self.update_entry_group, + default_timeout=None, + client_info=client_info, + ), + self.get_entry_group: gapic_v1.method.wrap_method( + self.get_entry_group, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_entry_group: gapic_v1.method.wrap_method( + self.delete_entry_group, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_entry_groups: gapic_v1.method.wrap_method( + self.list_entry_groups, + default_timeout=None, + client_info=client_info, + ), + self.create_entry: gapic_v1.method.wrap_method( + self.create_entry, + default_timeout=None, + client_info=client_info, + ), + self.update_entry: gapic_v1.method.wrap_method( + self.update_entry, + default_timeout=None, + client_info=client_info, + ), + self.delete_entry: gapic_v1.method.wrap_method( + self.delete_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_entry: gapic_v1.method.wrap_method( + self.get_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.lookup_entry: gapic_v1.method.wrap_method( + self.lookup_entry, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_entries: gapic_v1.method.wrap_method( + self.list_entries, + default_timeout=None, + client_info=client_info, + ), + self.create_tag_template: gapic_v1.method.wrap_method( + self.create_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.get_tag_template: gapic_v1.method.wrap_method( + self.get_tag_template, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_tag_template: gapic_v1.method.wrap_method( + self.update_tag_template, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag_template: gapic_v1.method.wrap_method( + self.delete_tag_template, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag_template_field: gapic_v1.method.wrap_method( + self.create_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.update_tag_template_field: gapic_v1.method.wrap_method( + self.update_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.rename_tag_template_field: gapic_v1.method.wrap_method( + self.rename_tag_template_field, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag_template_field: gapic_v1.method.wrap_method( + self.delete_tag_template_field, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag: gapic_v1.method.wrap_method( + self.create_tag, + default_timeout=None, + client_info=client_info, + ), + self.update_tag: gapic_v1.method.wrap_method( + self.update_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_tag: gapic_v1.method.wrap_method( + self.delete_tag, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_tags: gapic_v1.method.wrap_method( + self.list_tags, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + Union[ + datacatalog.SearchCatalogResponse, + Awaitable[datacatalog.SearchCatalogResponse] + ]]: + raise NotImplementedError() + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + Union[ + datacatalog.EntryGroup, + Awaitable[datacatalog.EntryGroup] + ]]: + raise NotImplementedError() + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + Union[ + datacatalog.ListEntryGroupsResponse, + Awaitable[datacatalog.ListEntryGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + Union[ + datacatalog.Entry, + Awaitable[datacatalog.Entry] + ]]: + raise NotImplementedError() + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + Union[ + datacatalog.ListEntriesResponse, + Awaitable[datacatalog.ListEntriesResponse] + ]]: + raise NotImplementedError() + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + Union[ + tags.TagTemplate, + Awaitable[tags.TagTemplate] + ]]: + raise NotImplementedError() + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + Union[ + tags.TagTemplateField, + Awaitable[tags.TagTemplateField] + ]]: + raise NotImplementedError() + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + Union[ + tags.Tag, + Awaitable[tags.Tag] + ]]: + raise NotImplementedError() + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + Union[ + tags.Tag, + Awaitable[tags.Tag] + ]]: + raise NotImplementedError() + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + Union[ + datacatalog.ListTagsResponse, + Awaitable[datacatalog.ListTagsResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DataCatalogTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py new file mode 100644 index 00000000..24ce3010 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py @@ -0,0 +1,1079 @@ +# -*- 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.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO + + +class DataCatalogGrpcTransport(DataCatalogTransport): + """gRPC backend transport for DataCatalog. + + Data Catalog API service allows clients to discover, + understand, and manage their data. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + datacatalog.SearchCatalogResponse]: + r"""Return a callable for the search catalog method over gRPC. + + Searches Data Catalog for multiple resources like entries, tags + that match a query. + + This is a custom method + (https://cloud.google.com/apis/design/custom_methods) and does + not return the complete resource, only the resource identifier + and high level fields. Clients can subsequentally call ``Get`` + methods. + + Note that Data Catalog search queries do not guarantee full + recall. Query results that match your query may not be returned, + even in subsequent result pages. Also note that results returned + (and not returned) can vary across repeated search queries. + + See `Data Catalog Search + Syntax `__ + for more information. + + Returns: + Callable[[~.SearchCatalogRequest], + ~.SearchCatalogResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_catalog' not in self._stubs: + self._stubs['search_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/SearchCatalog', + request_serializer=datacatalog.SearchCatalogRequest.serialize, + response_deserializer=datacatalog.SearchCatalogResponse.deserialize, + ) + return self._stubs['search_catalog'] + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the create entry group method over gRPC. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.CreateEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntryGroup', + request_serializer=datacatalog.CreateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['create_entry_group'] + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the update entry group method over gRPC. + + Updates an EntryGroup. The user should enable the Data Catalog + API in the project identified by the ``entry_group.name`` + parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntryGroup', + request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['update_entry_group'] + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + datacatalog.EntryGroup]: + r"""Return a callable for the get entry group method over gRPC. + + Gets an EntryGroup. + + Returns: + Callable[[~.GetEntryGroupRequest], + ~.EntryGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntryGroup', + request_serializer=datacatalog.GetEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['get_entry_group'] + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entry group method over gRPC. + + Deletes an EntryGroup. Only entry groups that do not contain + entries can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteEntryGroupRequest], + ~.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_entry_group' not in self._stubs: + self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntryGroup', + request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry_group'] + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + datacatalog.ListEntryGroupsResponse]: + r"""Return a callable for the list entry groups method over gRPC. + + Lists entry groups. + + Returns: + Callable[[~.ListEntryGroupsRequest], + ~.ListEntryGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: + self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntryGroups', + request_serializer=datacatalog.ListEntryGroupsRequest.serialize, + response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, + ) + return self._stubs['list_entry_groups'] + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the create entry method over gRPC. + + Creates an entry. Only entries of 'FILESET' type or + user-specified type can be created. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + A maximum of 100,000 entries may be created per entry group. + + Returns: + Callable[[~.CreateEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['create_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntry', + request_serializer=datacatalog.CreateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['create_entry'] + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the update entry method over gRPC. + + Updates an existing entry. Users should enable the Data Catalog + API in the project identified by the ``entry.name`` parameter + (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['update_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntry', + request_serializer=datacatalog.UpdateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['update_entry'] + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entry method over gRPC. + + Deletes an existing entry. Only entries created through + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] + method can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteEntryRequest], + ~.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_entry' not in self._stubs: + self._stubs['delete_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntry', + request_serializer=datacatalog.DeleteEntryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry'] + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the get entry method over gRPC. + + Gets an entry. + + Returns: + Callable[[~.GetEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['get_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntry', + request_serializer=datacatalog.GetEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['get_entry'] + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + datacatalog.Entry]: + r"""Return a callable for the lookup entry method over gRPC. + + Get an entry by target resource name. This method + allows clients to use the resource name from the source + Google Cloud Platform service to get the Data Catalog + Entry. + + Returns: + Callable[[~.LookupEntryRequest], + ~.Entry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_entry' not in self._stubs: + self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/LookupEntry', + request_serializer=datacatalog.LookupEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['lookup_entry'] + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + datacatalog.ListEntriesResponse]: + r"""Return a callable for the list entries method over gRPC. + + Lists entries. + + Returns: + Callable[[~.ListEntriesRequest], + ~.ListEntriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entries' not in self._stubs: + self._stubs['list_entries'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntries', + request_serializer=datacatalog.ListEntriesRequest.serialize, + response_deserializer=datacatalog.ListEntriesResponse.deserialize, + ) + return self._stubs['list_entries'] + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the create tag template method over gRPC. + + Creates a tag template. The user should enable the Data Catalog + API in the project identified by the ``parent`` parameter (see + `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.CreateTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplate', + request_serializer=datacatalog.CreateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['create_tag_template'] + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the get tag template method over gRPC. + + Gets a tag template. + + Returns: + Callable[[~.GetTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetTagTemplate', + request_serializer=datacatalog.GetTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['get_tag_template'] + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + tags.TagTemplate]: + r"""Return a callable for the update tag template method over gRPC. + + Updates a tag template. This method cannot be used to update the + fields of a template. The tag template fields are represented as + separate resources and should be updated using their own + create/update/delete methods. Users should enable the Data + Catalog API in the project identified by the + ``tag_template.name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateTagTemplateRequest], + ~.TagTemplate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplate', + request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['update_tag_template'] + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag template method over gRPC. + + Deletes a tag template and all tags using the template. Users + should enable the Data Catalog API in the project identified by + the ``name`` parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteTagTemplateRequest], + ~.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_tag_template' not in self._stubs: + self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplate', + request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template'] + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the create tag template field method over gRPC. + + Creates a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``parent`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.CreateTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplateField', + request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['create_tag_template_field'] + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the update tag template field method over gRPC. + + Updates a field in a tag template. This method cannot be used to + update the field type. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplateField', + request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['update_tag_template_field'] + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + tags.TagTemplateField]: + r"""Return a callable for the rename tag template field method over gRPC. + + Renames a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``name`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.RenameTagTemplateFieldRequest], + ~.TagTemplateField]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field' not in self._stubs: + self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/RenameTagTemplateField', + request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field'] + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag template field method over gRPC. + + Deletes a field in a tag template and all uses of that field. + Users should enable the Data Catalog API in the project + identified by the ``name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteTagTemplateFieldRequest], + ~.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_tag_template_field' not in self._stubs: + self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplateField', + request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template_field'] + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + tags.Tag]: + r"""Return a callable for the create tag method over gRPC. + + Creates a tag on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The + project identified by the ``parent`` parameter for the + `tag `__ + and the `tag + template `__ + used to create the tag must be from the same organization. + + Returns: + Callable[[~.CreateTagRequest], + ~.Tag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['create_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTag', + request_serializer=datacatalog.CreateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['create_tag'] + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + tags.Tag]: + r"""Return a callable for the update tag method over gRPC. + + Updates an existing tag. + + Returns: + Callable[[~.UpdateTagRequest], + ~.Tag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['update_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTag', + request_serializer=datacatalog.UpdateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['update_tag'] + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete tag method over gRPC. + + Deletes a tag. + + Returns: + Callable[[~.DeleteTagRequest], + ~.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_tag' not in self._stubs: + self._stubs['delete_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTag', + request_serializer=datacatalog.DeleteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag'] + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + datacatalog.ListTagsResponse]: + r"""Return a callable for the list tags method over gRPC. + + Lists the tags on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. + + Returns: + Callable[[~.ListTagsRequest], + ~.ListTagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tags' not in self._stubs: + self._stubs['list_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListTags', + request_serializer=datacatalog.ListTagsRequest.serialize, + response_deserializer=datacatalog.ListTagsResponse.deserialize, + ) + return self._stubs['list_tags'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy for a resource. Replaces any + existing policy. Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entries.setIamPolicy`` to set policies on + entries. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. A ``NOT_FOUND`` + error is returned if the resource does not exist. An empty + policy is returned if the resource exists but does not have a + policy set on it. + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entries.getIamPolicy`` to get policies on + entries. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the caller's permissions on a resource. If the resource + does not exist, an empty set of permissions is returned (We + don't return a ``NOT_FOUND`` error). + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + A caller is not required to have Google IAM permission to make + this request. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DataCatalogGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py new file mode 100644 index 00000000..bc9a0d03 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py @@ -0,0 +1,1083 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import tags +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO +from .grpc import DataCatalogGrpcTransport + + +class DataCatalogGrpcAsyncIOTransport(DataCatalogTransport): + """gRPC AsyncIO backend transport for DataCatalog. + + Data Catalog API service allows clients to discover, + understand, and manage their data. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 search_catalog(self) -> Callable[ + [datacatalog.SearchCatalogRequest], + Awaitable[datacatalog.SearchCatalogResponse]]: + r"""Return a callable for the search catalog method over gRPC. + + Searches Data Catalog for multiple resources like entries, tags + that match a query. + + This is a custom method + (https://cloud.google.com/apis/design/custom_methods) and does + not return the complete resource, only the resource identifier + and high level fields. Clients can subsequentally call ``Get`` + methods. + + Note that Data Catalog search queries do not guarantee full + recall. Query results that match your query may not be returned, + even in subsequent result pages. Also note that results returned + (and not returned) can vary across repeated search queries. + + See `Data Catalog Search + Syntax `__ + for more information. + + Returns: + Callable[[~.SearchCatalogRequest], + Awaitable[~.SearchCatalogResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_catalog' not in self._stubs: + self._stubs['search_catalog'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/SearchCatalog', + request_serializer=datacatalog.SearchCatalogRequest.serialize, + response_deserializer=datacatalog.SearchCatalogResponse.deserialize, + ) + return self._stubs['search_catalog'] + + @property + def create_entry_group(self) -> Callable[ + [datacatalog.CreateEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the create entry group method over gRPC. + + A maximum of 10,000 entry groups may be created per organization + across all locations. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.CreateEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntryGroup', + request_serializer=datacatalog.CreateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['create_entry_group'] + + @property + def update_entry_group(self) -> Callable[ + [datacatalog.UpdateEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the update entry group method over gRPC. + + Updates an EntryGroup. The user should enable the Data Catalog + API in the project identified by the ``entry_group.name`` + parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntryGroup', + request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['update_entry_group'] + + @property + def get_entry_group(self) -> Callable[ + [datacatalog.GetEntryGroupRequest], + Awaitable[datacatalog.EntryGroup]]: + r"""Return a callable for the get entry group method over gRPC. + + Gets an EntryGroup. + + Returns: + Callable[[~.GetEntryGroupRequest], + Awaitable[~.EntryGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_group' not in self._stubs: + self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntryGroup', + request_serializer=datacatalog.GetEntryGroupRequest.serialize, + response_deserializer=datacatalog.EntryGroup.deserialize, + ) + return self._stubs['get_entry_group'] + + @property + def delete_entry_group(self) -> Callable[ + [datacatalog.DeleteEntryGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entry group method over gRPC. + + Deletes an EntryGroup. Only entry groups that do not contain + entries can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteEntryGroupRequest], + 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_entry_group' not in self._stubs: + self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntryGroup', + request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry_group'] + + @property + def list_entry_groups(self) -> Callable[ + [datacatalog.ListEntryGroupsRequest], + Awaitable[datacatalog.ListEntryGroupsResponse]]: + r"""Return a callable for the list entry groups method over gRPC. + + Lists entry groups. + + Returns: + Callable[[~.ListEntryGroupsRequest], + Awaitable[~.ListEntryGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: + self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntryGroups', + request_serializer=datacatalog.ListEntryGroupsRequest.serialize, + response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, + ) + return self._stubs['list_entry_groups'] + + @property + def create_entry(self) -> Callable[ + [datacatalog.CreateEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the create entry method over gRPC. + + Creates an entry. Only entries of 'FILESET' type or + user-specified type can be created. + + Users should enable the Data Catalog API in the project + identified by the ``parent`` parameter (see [Data Catalog + Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + A maximum of 100,000 entries may be created per entry group. + + Returns: + Callable[[~.CreateEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['create_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntry', + request_serializer=datacatalog.CreateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['create_entry'] + + @property + def update_entry(self) -> Callable[ + [datacatalog.UpdateEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the update entry method over gRPC. + + Updates an existing entry. Users should enable the Data Catalog + API in the project identified by the ``entry.name`` parameter + (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['update_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntry', + request_serializer=datacatalog.UpdateEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['update_entry'] + + @property + def delete_entry(self) -> Callable[ + [datacatalog.DeleteEntryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entry method over gRPC. + + Deletes an existing entry. Only entries created through + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] + method can be deleted. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteEntryRequest], + 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_entry' not in self._stubs: + self._stubs['delete_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntry', + request_serializer=datacatalog.DeleteEntryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entry'] + + @property + def get_entry(self) -> Callable[ + [datacatalog.GetEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the get entry method over gRPC. + + Gets an entry. + + Returns: + Callable[[~.GetEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entry' not in self._stubs: + self._stubs['get_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntry', + request_serializer=datacatalog.GetEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['get_entry'] + + @property + def lookup_entry(self) -> Callable[ + [datacatalog.LookupEntryRequest], + Awaitable[datacatalog.Entry]]: + r"""Return a callable for the lookup entry method over gRPC. + + Get an entry by target resource name. This method + allows clients to use the resource name from the source + Google Cloud Platform service to get the Data Catalog + Entry. + + Returns: + Callable[[~.LookupEntryRequest], + Awaitable[~.Entry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_entry' not in self._stubs: + self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/LookupEntry', + request_serializer=datacatalog.LookupEntryRequest.serialize, + response_deserializer=datacatalog.Entry.deserialize, + ) + return self._stubs['lookup_entry'] + + @property + def list_entries(self) -> Callable[ + [datacatalog.ListEntriesRequest], + Awaitable[datacatalog.ListEntriesResponse]]: + r"""Return a callable for the list entries method over gRPC. + + Lists entries. + + Returns: + Callable[[~.ListEntriesRequest], + Awaitable[~.ListEntriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entries' not in self._stubs: + self._stubs['list_entries'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntries', + request_serializer=datacatalog.ListEntriesRequest.serialize, + response_deserializer=datacatalog.ListEntriesResponse.deserialize, + ) + return self._stubs['list_entries'] + + @property + def create_tag_template(self) -> Callable[ + [datacatalog.CreateTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the create tag template method over gRPC. + + Creates a tag template. The user should enable the Data Catalog + API in the project identified by the ``parent`` parameter (see + `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.CreateTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplate', + request_serializer=datacatalog.CreateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['create_tag_template'] + + @property + def get_tag_template(self) -> Callable[ + [datacatalog.GetTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the get tag template method over gRPC. + + Gets a tag template. + + Returns: + Callable[[~.GetTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetTagTemplate', + request_serializer=datacatalog.GetTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['get_tag_template'] + + @property + def update_tag_template(self) -> Callable[ + [datacatalog.UpdateTagTemplateRequest], + Awaitable[tags.TagTemplate]]: + r"""Return a callable for the update tag template method over gRPC. + + Updates a tag template. This method cannot be used to update the + fields of a template. The tag template fields are represented as + separate resources and should be updated using their own + create/update/delete methods. Users should enable the Data + Catalog API in the project identified by the + ``tag_template.name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateTagTemplateRequest], + Awaitable[~.TagTemplate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template' not in self._stubs: + self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplate', + request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, + response_deserializer=tags.TagTemplate.deserialize, + ) + return self._stubs['update_tag_template'] + + @property + def delete_tag_template(self) -> Callable[ + [datacatalog.DeleteTagTemplateRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag template method over gRPC. + + Deletes a tag template and all tags using the template. Users + should enable the Data Catalog API in the project identified by + the ``name`` parameter (see [Data Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteTagTemplateRequest], + 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_tag_template' not in self._stubs: + self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplate', + request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template'] + + @property + def create_tag_template_field(self) -> Callable[ + [datacatalog.CreateTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the create tag template field method over gRPC. + + Creates a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``parent`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.CreateTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplateField', + request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['create_tag_template_field'] + + @property + def update_tag_template_field(self) -> Callable[ + [datacatalog.UpdateTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the update tag template field method over gRPC. + + Updates a field in a tag template. This method cannot be used to + update the field type. Users should enable the Data Catalog API + in the project identified by the ``name`` parameter (see [Data + Catalog Resource Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.UpdateTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: + self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplateField', + request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['update_tag_template_field'] + + @property + def rename_tag_template_field(self) -> Callable[ + [datacatalog.RenameTagTemplateFieldRequest], + Awaitable[tags.TagTemplateField]]: + r"""Return a callable for the rename tag template field method over gRPC. + + Renames a field in a tag template. The user should enable the + Data Catalog API in the project identified by the ``name`` + parameter (see `Data Catalog Resource + Project `__ + for more information). + + Returns: + Callable[[~.RenameTagTemplateFieldRequest], + Awaitable[~.TagTemplateField]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'rename_tag_template_field' not in self._stubs: + self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/RenameTagTemplateField', + request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, + response_deserializer=tags.TagTemplateField.deserialize, + ) + return self._stubs['rename_tag_template_field'] + + @property + def delete_tag_template_field(self) -> Callable[ + [datacatalog.DeleteTagTemplateFieldRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag template field method over gRPC. + + Deletes a field in a tag template and all uses of that field. + Users should enable the Data Catalog API in the project + identified by the ``name`` parameter (see [Data Catalog Resource + Project] + (https://cloud.google.com/data-catalog/docs/concepts/resource-project) + for more information). + + Returns: + Callable[[~.DeleteTagTemplateFieldRequest], + 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_tag_template_field' not in self._stubs: + self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplateField', + request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag_template_field'] + + @property + def create_tag(self) -> Callable[ + [datacatalog.CreateTagRequest], + Awaitable[tags.Tag]]: + r"""Return a callable for the create tag method over gRPC. + + Creates a tag on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The + project identified by the ``parent`` parameter for the + `tag `__ + and the `tag + template `__ + used to create the tag must be from the same organization. + + Returns: + Callable[[~.CreateTagRequest], + Awaitable[~.Tag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['create_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTag', + request_serializer=datacatalog.CreateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['create_tag'] + + @property + def update_tag(self) -> Callable[ + [datacatalog.UpdateTagRequest], + Awaitable[tags.Tag]]: + r"""Return a callable for the update tag method over gRPC. + + Updates an existing tag. + + Returns: + Callable[[~.UpdateTagRequest], + Awaitable[~.Tag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag' not in self._stubs: + self._stubs['update_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTag', + request_serializer=datacatalog.UpdateTagRequest.serialize, + response_deserializer=tags.Tag.deserialize, + ) + return self._stubs['update_tag'] + + @property + def delete_tag(self) -> Callable[ + [datacatalog.DeleteTagRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tag method over gRPC. + + Deletes a tag. + + Returns: + Callable[[~.DeleteTagRequest], + 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_tag' not in self._stubs: + self._stubs['delete_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTag', + request_serializer=datacatalog.DeleteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_tag'] + + @property + def list_tags(self) -> Callable[ + [datacatalog.ListTagsRequest], + Awaitable[datacatalog.ListTagsResponse]]: + r"""Return a callable for the list tags method over gRPC. + + Lists the tags on an + [Entry][google.cloud.datacatalog.v1beta1.Entry]. + + Returns: + Callable[[~.ListTagsRequest], + Awaitable[~.ListTagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tags' not in self._stubs: + self._stubs['list_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/ListTags', + request_serializer=datacatalog.ListTagsRequest.serialize, + response_deserializer=datacatalog.ListTagsResponse.deserialize, + ) + return self._stubs['list_tags'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy for a resource. Replaces any + existing policy. Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on + tag templates. + - ``datacatalog.entries.setIamPolicy`` to set policies on + entries. + - ``datacatalog.entryGroups.setIamPolicy`` to set policies on + entry groups. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. A ``NOT_FOUND`` + error is returned if the resource does not exist. An empty + policy is returned if the resource exists but does not have a + policy set on it. + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + Callers must have following Google IAM permission + + - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on + tag templates. + - ``datacatalog.entries.getIamPolicy`` to get policies on + entries. + - ``datacatalog.entryGroups.getIamPolicy`` to get policies on + entry groups. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the caller's permissions on a resource. If the resource + does not exist, an empty set of permissions is returned (We + don't return a ``NOT_FOUND`` error). + + Supported resources are: + + - Tag templates. + - Entries. + - Entry groups. Note, this method cannot be used to manage + policies for BigQuery, Pub/Sub and any external Google Cloud + Platform resources synced to Data Catalog. + + A caller is not required to have Google IAM permission to make + this request. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.DataCatalog/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DataCatalogGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py new file mode 100644 index 00000000..3d4e08a0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__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 PolicyTagManagerClient +from .async_client import PolicyTagManagerAsyncClient + +__all__ = ( + 'PolicyTagManagerClient', + 'PolicyTagManagerAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py new file mode 100644 index 00000000..e5af6b24 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py @@ -0,0 +1,1263 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport +from .client import PolicyTagManagerClient + + +class PolicyTagManagerAsyncClient: + """The policy tag manager API service allows clients to manage + their taxonomies and policy tags. + """ + + _client: PolicyTagManagerClient + + DEFAULT_ENDPOINT = PolicyTagManagerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyTagManagerClient.DEFAULT_MTLS_ENDPOINT + + policy_tag_path = staticmethod(PolicyTagManagerClient.policy_tag_path) + parse_policy_tag_path = staticmethod(PolicyTagManagerClient.parse_policy_tag_path) + taxonomy_path = staticmethod(PolicyTagManagerClient.taxonomy_path) + parse_taxonomy_path = staticmethod(PolicyTagManagerClient.parse_taxonomy_path) + common_billing_account_path = staticmethod(PolicyTagManagerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PolicyTagManagerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PolicyTagManagerClient.common_folder_path) + parse_common_folder_path = staticmethod(PolicyTagManagerClient.parse_common_folder_path) + common_organization_path = staticmethod(PolicyTagManagerClient.common_organization_path) + parse_common_organization_path = staticmethod(PolicyTagManagerClient.parse_common_organization_path) + common_project_path = staticmethod(PolicyTagManagerClient.common_project_path) + parse_common_project_path = staticmethod(PolicyTagManagerClient.parse_common_project_path) + common_location_path = staticmethod(PolicyTagManagerClient.common_location_path) + parse_common_location_path = staticmethod(PolicyTagManagerClient.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: + PolicyTagManagerAsyncClient: The constructed client. + """ + return PolicyTagManagerClient.from_service_account_info.__func__(PolicyTagManagerAsyncClient, 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: + PolicyTagManagerAsyncClient: The constructed client. + """ + return PolicyTagManagerClient.from_service_account_file.__func__(PolicyTagManagerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyTagManagerTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PolicyTagManagerClient).get_transport_class, type(PolicyTagManagerClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PolicyTagManagerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager 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, ~.PolicyTagManagerTransport]): 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 = PolicyTagManagerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_taxonomy(self, + request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, + *, + parent: str = None, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Creates a taxonomy in the specified project. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTaxonomyRequest, dict]): + The request object. Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. + parent (:class:`str`): + Required. Resource name of the + project that the taxonomy will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + taxonomy (:class:`google.cloud.datacatalog_v1beta1.types.Taxonomy`): + The taxonomy to be created. + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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, taxonomy]) + if request is 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 = policytagmanager.CreateTaxonomyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if taxonomy is not None: + request.taxonomy = taxonomy + + # 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_taxonomy, + default_timeout=None, + client_info=DEFAULT_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 delete_taxonomy(self, + request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a taxonomy. This operation will also delete + all policy tags in this taxonomy along with their + associated policies. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTaxonomyRequest, dict]): + The request object. Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. + name (:class:`str`): + Required. Resource name of the + taxonomy to be deleted. All policy tags + in this taxonomy will also be deleted. + + 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 = policytagmanager.DeleteTaxonomyRequest(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_taxonomy, + default_timeout=None, + client_info=DEFAULT_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 update_taxonomy(self, + request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, + *, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Updates a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTaxonomyRequest, dict]): + The request object. Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. + taxonomy (:class:`google.cloud.datacatalog_v1beta1.types.Taxonomy`): + The taxonomy to update. Only description, display_name, + and activated policy types can be updated. + + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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([taxonomy]) + if request is 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 = policytagmanager.UpdateTaxonomyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if taxonomy is not None: + request.taxonomy = taxonomy + + # 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_taxonomy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("taxonomy.name", request.taxonomy.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_taxonomies(self, + request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTaxonomiesAsyncPager: + r"""Lists all taxonomies in a project in a particular + location that the caller has permission to view. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListTaxonomiesRequest, dict]): + The request object. Request message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + parent (:class:`str`): + Required. Resource name of the + project to list the taxonomies of. + + 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListTaxonomiesAsyncPager: + Response message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + + 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 = policytagmanager.ListTaxonomiesRequest(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_taxonomies, + default_timeout=None, + client_info=DEFAULT_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.ListTaxonomiesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_taxonomy(self, + request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Gets a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetTaxonomyRequest, dict]): + The request object. Request message for + [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. + name (:class:`str`): + Required. Resource name of the + requested taxonomy. + + 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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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 = policytagmanager.GetTaxonomyRequest(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_taxonomy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_policy_tag(self, + request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, + *, + parent: str = None, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Creates a policy tag in the specified taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreatePolicyTagRequest, dict]): + The request object. Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. + parent (:class:`str`): + Required. Resource name of the + taxonomy that the policy tag will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_tag (:class:`google.cloud.datacatalog_v1beta1.types.PolicyTag`): + The policy tag to be created. + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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, policy_tag]) + if request is 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 = policytagmanager.CreatePolicyTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_tag is not None: + request.policy_tag = policy_tag + + # 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_policy_tag, + default_timeout=None, + client_info=DEFAULT_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 delete_policy_tag(self, + request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a policy tag. Also deletes all of its + descendant policy tags. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeletePolicyTagRequest, dict]): + The request object. Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. + name (:class:`str`): + Required. Resource name of the policy + tag to be deleted. All of its descendant + policy tags will also be deleted. + + 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 = policytagmanager.DeletePolicyTagRequest(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_policy_tag, + default_timeout=None, + client_info=DEFAULT_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 update_policy_tag(self, + request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, + *, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Updates a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdatePolicyTagRequest, dict]): + The request object. Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. + policy_tag (:class:`google.cloud.datacatalog_v1beta1.types.PolicyTag`): + The policy tag to update. Only the description, + display_name, and parent_policy_tag fields can be + updated. + + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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([policy_tag]) + if request is 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 = policytagmanager.UpdatePolicyTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_tag is not None: + request.policy_tag = policy_tag + + # 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_policy_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("policy_tag.name", request.policy_tag.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_policy_tags(self, + request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPolicyTagsAsyncPager: + r"""Lists all policy tags in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListPolicyTagsRequest, dict]): + The request object. Request message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + parent (:class:`str`): + Required. Resource name of the + taxonomy to list the policy tags of. + + 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListPolicyTagsAsyncPager: + Response message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + + 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 = policytagmanager.ListPolicyTagsRequest(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_policy_tags, + default_timeout=None, + client_info=DEFAULT_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.ListPolicyTagsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_policy_tag(self, + request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Gets a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetPolicyTagRequest, dict]): + The request object. Request message for + [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. + name (:class:`str`): + Required. Resource name of the + requested policy tag. + + 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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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 = policytagmanager.GetPolicyTagRequest(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_policy_tag, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a taxonomy or a policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy for a taxonomy or a policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified taxonomy or policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py new file mode 100644 index 00000000..7ce73c28 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py @@ -0,0 +1,1466 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PolicyTagManagerGrpcTransport +from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport + + +class PolicyTagManagerClientMeta(type): + """Metaclass for the PolicyTagManager 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[PolicyTagManagerTransport]] + _transport_registry["grpc"] = PolicyTagManagerGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyTagManagerGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PolicyTagManagerTransport]: + """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 PolicyTagManagerClient(metaclass=PolicyTagManagerClientMeta): + """The policy tag manager API service allows clients to manage + their taxonomies and policy tags. + """ + + @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 = "datacatalog.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: + PolicyTagManagerClient: 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: + PolicyTagManagerClient: 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) -> PolicyTagManagerTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def policy_tag_path(project: str,location: str,taxonomy: str,policy_tag: str,) -> str: + """Returns a fully-qualified policy_tag string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) + + @staticmethod + def parse_policy_tag_path(path: str) -> Dict[str,str]: + """Parses a policy_tag path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?P.+?)/policyTags/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: + """Returns a fully-qualified taxonomy string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + + @staticmethod + def parse_taxonomy_path(path: str) -> Dict[str,str]: + """Parses a taxonomy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager 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, PolicyTagManagerTransport]): 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, PolicyTagManagerTransport): + # transport is a PolicyTagManagerTransport 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=True, + ) + + def create_taxonomy(self, + request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, + *, + parent: str = None, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Creates a taxonomy in the specified project. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreateTaxonomyRequest, dict]): + The request object. Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. + parent (str): + Required. Resource name of the + project that the taxonomy will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): + The taxonomy to be created. + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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, taxonomy]) + if request is 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 policytagmanager.CreateTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.CreateTaxonomyRequest): + request = policytagmanager.CreateTaxonomyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if taxonomy is not None: + request.taxonomy = taxonomy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_taxonomy] + + # 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 delete_taxonomy(self, + request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a taxonomy. This operation will also delete + all policy tags in this taxonomy along with their + associated policies. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTaxonomyRequest, dict]): + The request object. Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. + name (str): + Required. Resource name of the + taxonomy to be deleted. All policy tags + in this taxonomy will also be deleted. + + 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 policytagmanager.DeleteTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.DeleteTaxonomyRequest): + request = policytagmanager.DeleteTaxonomyRequest(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_taxonomy] + + # Certain fields should be 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 update_taxonomy(self, + request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, + *, + taxonomy: policytagmanager.Taxonomy = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Updates a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTaxonomyRequest, dict]): + The request object. Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. + taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): + The taxonomy to update. Only description, display_name, + and activated policy types can be updated. + + This corresponds to the ``taxonomy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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([taxonomy]) + if request is 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 policytagmanager.UpdateTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.UpdateTaxonomyRequest): + request = policytagmanager.UpdateTaxonomyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if taxonomy is not None: + request.taxonomy = taxonomy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_taxonomy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("taxonomy.name", request.taxonomy.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_taxonomies(self, + request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTaxonomiesPager: + r"""Lists all taxonomies in a project in a particular + location that the caller has permission to view. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListTaxonomiesRequest, dict]): + The request object. Request message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + parent (str): + Required. Resource name of the + project to list the taxonomies of. + + 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListTaxonomiesPager: + Response message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + + 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 policytagmanager.ListTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.ListTaxonomiesRequest): + request = policytagmanager.ListTaxonomiesRequest(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_taxonomies] + + # 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.ListTaxonomiesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_taxonomy(self, + request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.Taxonomy: + r"""Gets a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetTaxonomyRequest, dict]): + The request object. Request message for + [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. + name (str): + Required. Resource name of the + requested taxonomy. + + 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.datacatalog_v1beta1.types.Taxonomy: + A taxonomy is a collection of policy tags that classify data along a common + axis. For instance a data *sensitivity* taxonomy + could contain policy tags denoting PII such as age, + zipcode, and SSN. A data *origin* taxonomy could + contain policy tags to distinguish user data, + employee data, partner data, public data. + + """ + # 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 policytagmanager.GetTaxonomyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.GetTaxonomyRequest): + request = policytagmanager.GetTaxonomyRequest(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_taxonomy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_policy_tag(self, + request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, + *, + parent: str = None, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Creates a policy tag in the specified taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.CreatePolicyTagRequest, dict]): + The request object. Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. + parent (str): + Required. Resource name of the + taxonomy that the policy tag will belong + to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): + The policy tag to be created. + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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, policy_tag]) + if request is 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 policytagmanager.CreatePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.CreatePolicyTagRequest): + request = policytagmanager.CreatePolicyTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_tag is not None: + request.policy_tag = policy_tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_policy_tag] + + # 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 delete_policy_tag(self, + request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a policy tag. Also deletes all of its + descendant policy tags. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.DeletePolicyTagRequest, dict]): + The request object. Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. + name (str): + Required. Resource name of the policy + tag to be deleted. All of its descendant + policy tags will also be deleted. + + 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 policytagmanager.DeletePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.DeletePolicyTagRequest): + request = policytagmanager.DeletePolicyTagRequest(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_policy_tag] + + # Certain fields should be 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 update_policy_tag(self, + request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, + *, + policy_tag: policytagmanager.PolicyTag = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Updates a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.UpdatePolicyTagRequest, dict]): + The request object. Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. + policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): + The policy tag to update. Only the description, + display_name, and parent_policy_tag fields can be + updated. + + This corresponds to the ``policy_tag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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([policy_tag]) + if request is 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 policytagmanager.UpdatePolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.UpdatePolicyTagRequest): + request = policytagmanager.UpdatePolicyTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if policy_tag is not None: + request.policy_tag = policy_tag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_policy_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("policy_tag.name", request.policy_tag.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_policy_tags(self, + request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPolicyTagsPager: + r"""Lists all policy tags in a taxonomy. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ListPolicyTagsRequest, dict]): + The request object. Request message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + parent (str): + Required. Resource name of the + taxonomy to list the policy tags of. + + 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListPolicyTagsPager: + Response message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + + 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 policytagmanager.ListPolicyTagsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.ListPolicyTagsRequest): + request = policytagmanager.ListPolicyTagsRequest(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_policy_tags] + + # 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.ListPolicyTagsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_policy_tag(self, + request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanager.PolicyTag: + r"""Gets a policy tag. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.GetPolicyTagRequest, dict]): + The request object. Request message for + [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. + name (str): + Required. Resource name of the + requested policy tag. + + 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.datacatalog_v1beta1.types.PolicyTag: + Denotes one policy tag in a taxonomy + (e.g. ssn). Policy Tags can be defined + in a hierarchy. For example, consider + the following hierarchy: Geolocation + -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three + child policy tags: "LatLong", "City", + and "ZipCode". + + """ + # 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 policytagmanager.GetPolicyTagRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanager.GetPolicyTagRequest): + request = policytagmanager.GetPolicyTagRequest(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_policy_tag] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a taxonomy or a policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy for a taxonomy or a policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified taxonomy or policy tag. + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py new file mode 100644 index 00000000..6ccf41e2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py @@ -0,0 +1,262 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.datacatalog_v1beta1.types import policytagmanager + + +class ListTaxonomiesPager: + """A pager for iterating through ``list_taxonomies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``taxonomies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTaxonomies`` requests and continue to iterate + through the ``taxonomies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` + 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[..., policytagmanager.ListTaxonomiesResponse], + request: policytagmanager.ListTaxonomiesRequest, + response: policytagmanager.ListTaxonomiesResponse, + *, + 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.datacatalog_v1beta1.types.ListTaxonomiesRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse): + 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 = policytagmanager.ListTaxonomiesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policytagmanager.ListTaxonomiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[policytagmanager.Taxonomy]: + for page in self.pages: + yield from page.taxonomies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTaxonomiesAsyncPager: + """A pager for iterating through ``list_taxonomies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``taxonomies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTaxonomies`` requests and continue to iterate + through the ``taxonomies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` + 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[policytagmanager.ListTaxonomiesResponse]], + request: policytagmanager.ListTaxonomiesRequest, + response: policytagmanager.ListTaxonomiesResponse, + *, + 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.datacatalog_v1beta1.types.ListTaxonomiesRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse): + 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 = policytagmanager.ListTaxonomiesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policytagmanager.ListTaxonomiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[policytagmanager.Taxonomy]: + async def async_generator(): + async for page in self.pages: + for response in page.taxonomies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPolicyTagsPager: + """A pager for iterating through ``list_policy_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_tags`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicyTags`` requests and continue to iterate + through the ``policy_tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` + 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[..., policytagmanager.ListPolicyTagsResponse], + request: policytagmanager.ListPolicyTagsRequest, + response: policytagmanager.ListPolicyTagsResponse, + *, + 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.datacatalog_v1beta1.types.ListPolicyTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse): + 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 = policytagmanager.ListPolicyTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policytagmanager.ListPolicyTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[policytagmanager.PolicyTag]: + for page in self.pages: + yield from page.policy_tags + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPolicyTagsAsyncPager: + """A pager for iterating through ``list_policy_tags`` requests. + + This class thinly wraps an initial + :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_tags`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicyTags`` requests and continue to iterate + through the ``policy_tags`` field on the + corresponding responses. + + All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` + 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[policytagmanager.ListPolicyTagsResponse]], + request: policytagmanager.ListPolicyTagsRequest, + response: policytagmanager.ListPolicyTagsResponse, + *, + 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.datacatalog_v1beta1.types.ListPolicyTagsRequest): + The initial request object. + response (google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse): + 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 = policytagmanager.ListPolicyTagsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[policytagmanager.ListPolicyTagsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[policytagmanager.PolicyTag]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_tags: + 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/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py new file mode 100644 index 00000000..d76a9c05 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/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 PolicyTagManagerTransport +from .grpc import PolicyTagManagerGrpcTransport +from .grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerTransport]] +_transport_registry['grpc'] = PolicyTagManagerGrpcTransport +_transport_registry['grpc_asyncio'] = PolicyTagManagerGrpcAsyncIOTransport + +__all__ = ( + 'PolicyTagManagerTransport', + 'PolicyTagManagerGrpcTransport', + 'PolicyTagManagerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py new file mode 100644 index 00000000..0e61f950 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py @@ -0,0 +1,317 @@ +# -*- 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 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.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +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-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PolicyTagManagerTransport(abc.ABC): + """Abstract transport class for PolicyTagManager.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_taxonomy: gapic_v1.method.wrap_method( + self.create_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.delete_taxonomy: gapic_v1.method.wrap_method( + self.delete_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.update_taxonomy: gapic_v1.method.wrap_method( + self.update_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.list_taxonomies: gapic_v1.method.wrap_method( + self.list_taxonomies, + default_timeout=None, + client_info=client_info, + ), + self.get_taxonomy: gapic_v1.method.wrap_method( + self.get_taxonomy, + default_timeout=None, + client_info=client_info, + ), + self.create_policy_tag: gapic_v1.method.wrap_method( + self.create_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_policy_tag: gapic_v1.method.wrap_method( + self.delete_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.update_policy_tag: gapic_v1.method.wrap_method( + self.update_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.list_policy_tags: gapic_v1.method.wrap_method( + self.list_policy_tags, + default_timeout=None, + client_info=client_info, + ), + self.get_policy_tag: gapic_v1.method.wrap_method( + self.get_policy_tag, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + Union[ + policytagmanager.ListTaxonomiesResponse, + Awaitable[policytagmanager.ListTaxonomiesResponse] + ]]: + raise NotImplementedError() + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + Union[ + policytagmanager.Taxonomy, + Awaitable[policytagmanager.Taxonomy] + ]]: + raise NotImplementedError() + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + Union[ + policytagmanager.ListPolicyTagsResponse, + Awaitable[policytagmanager.ListPolicyTagsResponse] + ]]: + raise NotImplementedError() + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + Union[ + policytagmanager.PolicyTag, + Awaitable[policytagmanager.PolicyTag] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PolicyTagManagerTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py new file mode 100644 index 00000000..63c211cb --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- 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.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO + + +class PolicyTagManagerGrpcTransport(PolicyTagManagerTransport): + """gRPC backend transport for PolicyTagManager. + + The policy tag manager API service allows clients to manage + their taxonomies and policy tags. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the create taxonomy method over gRPC. + + Creates a taxonomy in the specified project. + + Returns: + Callable[[~.CreateTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreateTaxonomy', + request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['create_taxonomy'] + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete taxonomy method over gRPC. + + Deletes a taxonomy. This operation will also delete + all policy tags in this taxonomy along with their + associated policies. + + Returns: + Callable[[~.DeleteTaxonomyRequest], + ~.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_taxonomy' not in self._stubs: + self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeleteTaxonomy', + request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_taxonomy'] + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the update taxonomy method over gRPC. + + Updates a taxonomy. + + Returns: + Callable[[~.UpdateTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdateTaxonomy', + request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['update_taxonomy'] + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + policytagmanager.ListTaxonomiesResponse]: + r"""Return a callable for the list taxonomies method over gRPC. + + Lists all taxonomies in a project in a particular + location that the caller has permission to view. + + Returns: + Callable[[~.ListTaxonomiesRequest], + ~.ListTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: + self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListTaxonomies', + request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, + response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, + ) + return self._stubs['list_taxonomies'] + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + policytagmanager.Taxonomy]: + r"""Return a callable for the get taxonomy method over gRPC. + + Gets a taxonomy. + + Returns: + Callable[[~.GetTaxonomyRequest], + ~.Taxonomy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetTaxonomy', + request_serializer=policytagmanager.GetTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['get_taxonomy'] + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the create policy tag method over gRPC. + + Creates a policy tag in the specified taxonomy. + + Returns: + Callable[[~.CreatePolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreatePolicyTag', + request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['create_policy_tag'] + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete policy tag method over gRPC. + + Deletes a policy tag. Also deletes all of its + descendant policy tags. + + Returns: + Callable[[~.DeletePolicyTagRequest], + ~.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_policy_tag' not in self._stubs: + self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeletePolicyTag', + request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_policy_tag'] + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the update policy tag method over gRPC. + + Updates a policy tag. + + Returns: + Callable[[~.UpdatePolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdatePolicyTag', + request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['update_policy_tag'] + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + policytagmanager.ListPolicyTagsResponse]: + r"""Return a callable for the list policy tags method over gRPC. + + Lists all policy tags in a taxonomy. + + Returns: + Callable[[~.ListPolicyTagsRequest], + ~.ListPolicyTagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: + self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListPolicyTags', + request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, + response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, + ) + return self._stubs['list_policy_tags'] + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + policytagmanager.PolicyTag]: + r"""Return a callable for the get policy tag method over gRPC. + + Gets a policy tag. + + Returns: + Callable[[~.GetPolicyTagRequest], + ~.PolicyTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetPolicyTag', + request_serializer=policytagmanager.GetPolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['get_policy_tag'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a taxonomy or a policy tag. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy for a taxonomy or a policy tag. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified taxonomy or policy tag. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'PolicyTagManagerGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py new file mode 100644 index 00000000..b7c1b991 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py @@ -0,0 +1,579 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO +from .grpc import PolicyTagManagerGrpcTransport + + +class PolicyTagManagerGrpcAsyncIOTransport(PolicyTagManagerTransport): + """gRPC AsyncIO backend transport for PolicyTagManager. + + The policy tag manager API service allows clients to manage + their taxonomies and policy tags. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 create_taxonomy(self) -> Callable[ + [policytagmanager.CreateTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the create taxonomy method over gRPC. + + Creates a taxonomy in the specified project. + + Returns: + Callable[[~.CreateTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreateTaxonomy', + request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['create_taxonomy'] + + @property + def delete_taxonomy(self) -> Callable[ + [policytagmanager.DeleteTaxonomyRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete taxonomy method over gRPC. + + Deletes a taxonomy. This operation will also delete + all policy tags in this taxonomy along with their + associated policies. + + Returns: + Callable[[~.DeleteTaxonomyRequest], + 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_taxonomy' not in self._stubs: + self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeleteTaxonomy', + request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_taxonomy'] + + @property + def update_taxonomy(self) -> Callable[ + [policytagmanager.UpdateTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the update taxonomy method over gRPC. + + Updates a taxonomy. + + Returns: + Callable[[~.UpdateTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdateTaxonomy', + request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['update_taxonomy'] + + @property + def list_taxonomies(self) -> Callable[ + [policytagmanager.ListTaxonomiesRequest], + Awaitable[policytagmanager.ListTaxonomiesResponse]]: + r"""Return a callable for the list taxonomies method over gRPC. + + Lists all taxonomies in a project in a particular + location that the caller has permission to view. + + Returns: + Callable[[~.ListTaxonomiesRequest], + Awaitable[~.ListTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: + self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListTaxonomies', + request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, + response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, + ) + return self._stubs['list_taxonomies'] + + @property + def get_taxonomy(self) -> Callable[ + [policytagmanager.GetTaxonomyRequest], + Awaitable[policytagmanager.Taxonomy]]: + r"""Return a callable for the get taxonomy method over gRPC. + + Gets a taxonomy. + + Returns: + Callable[[~.GetTaxonomyRequest], + Awaitable[~.Taxonomy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: + self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetTaxonomy', + request_serializer=policytagmanager.GetTaxonomyRequest.serialize, + response_deserializer=policytagmanager.Taxonomy.deserialize, + ) + return self._stubs['get_taxonomy'] + + @property + def create_policy_tag(self) -> Callable[ + [policytagmanager.CreatePolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the create policy tag method over gRPC. + + Creates a policy tag in the specified taxonomy. + + Returns: + Callable[[~.CreatePolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreatePolicyTag', + request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['create_policy_tag'] + + @property + def delete_policy_tag(self) -> Callable[ + [policytagmanager.DeletePolicyTagRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete policy tag method over gRPC. + + Deletes a policy tag. Also deletes all of its + descendant policy tags. + + Returns: + Callable[[~.DeletePolicyTagRequest], + 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_policy_tag' not in self._stubs: + self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeletePolicyTag', + request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_policy_tag'] + + @property + def update_policy_tag(self) -> Callable[ + [policytagmanager.UpdatePolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the update policy tag method over gRPC. + + Updates a policy tag. + + Returns: + Callable[[~.UpdatePolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdatePolicyTag', + request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['update_policy_tag'] + + @property + def list_policy_tags(self) -> Callable[ + [policytagmanager.ListPolicyTagsRequest], + Awaitable[policytagmanager.ListPolicyTagsResponse]]: + r"""Return a callable for the list policy tags method over gRPC. + + Lists all policy tags in a taxonomy. + + Returns: + Callable[[~.ListPolicyTagsRequest], + Awaitable[~.ListPolicyTagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: + self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListPolicyTags', + request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, + response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, + ) + return self._stubs['list_policy_tags'] + + @property + def get_policy_tag(self) -> Callable[ + [policytagmanager.GetPolicyTagRequest], + Awaitable[policytagmanager.PolicyTag]]: + r"""Return a callable for the get policy tag method over gRPC. + + Gets a policy tag. + + Returns: + Callable[[~.GetPolicyTagRequest], + Awaitable[~.PolicyTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: + self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetPolicyTag', + request_serializer=policytagmanager.GetPolicyTagRequest.serialize, + response_deserializer=policytagmanager.PolicyTag.deserialize, + ) + return self._stubs['get_policy_tag'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a taxonomy or a policy tag. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy for a taxonomy or a policy tag. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified taxonomy or policy tag. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PolicyTagManagerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py new file mode 100644 index 00000000..5e73ed2a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__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 PolicyTagManagerSerializationClient +from .async_client import PolicyTagManagerSerializationAsyncClient + +__all__ = ( + 'PolicyTagManagerSerializationClient', + 'PolicyTagManagerSerializationAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py new file mode 100644 index 00000000..8a7e1767 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py @@ -0,0 +1,288 @@ +# -*- 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 + +from google.api_core.client_options import 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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization +from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport +from .client import PolicyTagManagerSerializationClient + + +class PolicyTagManagerSerializationAsyncClient: + """Policy tag manager serialization API service allows clients + to manipulate their taxonomies and policy tags data with + serialized format. + """ + + _client: PolicyTagManagerSerializationClient + + DEFAULT_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_MTLS_ENDPOINT + + taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.taxonomy_path) + parse_taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.parse_taxonomy_path) + common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PolicyTagManagerSerializationClient.common_folder_path) + parse_common_folder_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_folder_path) + common_organization_path = staticmethod(PolicyTagManagerSerializationClient.common_organization_path) + parse_common_organization_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_organization_path) + common_project_path = staticmethod(PolicyTagManagerSerializationClient.common_project_path) + parse_common_project_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_project_path) + common_location_path = staticmethod(PolicyTagManagerSerializationClient.common_location_path) + parse_common_location_path = staticmethod(PolicyTagManagerSerializationClient.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: + PolicyTagManagerSerializationAsyncClient: The constructed client. + """ + return PolicyTagManagerSerializationClient.from_service_account_info.__func__(PolicyTagManagerSerializationAsyncClient, 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: + PolicyTagManagerSerializationAsyncClient: The constructed client. + """ + return PolicyTagManagerSerializationClient.from_service_account_file.__func__(PolicyTagManagerSerializationAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PolicyTagManagerSerializationTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerSerializationTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PolicyTagManagerSerializationClient).get_transport_class, type(PolicyTagManagerSerializationClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PolicyTagManagerSerializationTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager serialization 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, ~.PolicyTagManagerSerializationTransport]): 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 = PolicyTagManagerSerializationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def import_taxonomies(self, + request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ImportTaxonomiesResponse: + r"""Imports all taxonomies and their policy tags to a + project as new taxonomies. + + This method provides a bulk taxonomy / policy tag + creation using nested proto structure. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ImportTaxonomiesRequest, dict]): + The request object. Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.ImportTaxonomiesResponse: + Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + request = policytagmanagerserialization.ImportTaxonomiesRequest(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.import_taxonomies, + default_timeout=None, + client_info=DEFAULT_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 export_taxonomies(self, + request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ExportTaxonomiesResponse: + r"""Exports all taxonomies and their policy tags in a + project. + This method generates SerializedTaxonomy protos with + nested policy tags that can be used as an input for + future ImportTaxonomies calls. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ExportTaxonomiesRequest, dict]): + The request object. Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.ExportTaxonomiesResponse: + Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + request = policytagmanagerserialization.ExportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_taxonomies, + default_timeout=None, + client_info=DEFAULT_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 __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerSerializationAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py new file mode 100644 index 00000000..9be6bd9d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py @@ -0,0 +1,487 @@ +# -*- 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +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 + +OptionalRetry = Union[retries.Retry, object] + +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization +from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PolicyTagManagerSerializationGrpcTransport +from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport + + +class PolicyTagManagerSerializationClientMeta(type): + """Metaclass for the PolicyTagManagerSerialization 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[PolicyTagManagerSerializationTransport]] + _transport_registry["grpc"] = PolicyTagManagerSerializationGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyTagManagerSerializationGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PolicyTagManagerSerializationTransport]: + """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 PolicyTagManagerSerializationClient(metaclass=PolicyTagManagerSerializationClientMeta): + """Policy tag manager serialization API service allows clients + to manipulate their taxonomies and policy tags data with + serialized format. + """ + + @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 = "datacatalog.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: + PolicyTagManagerSerializationClient: 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: + PolicyTagManagerSerializationClient: 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) -> PolicyTagManagerSerializationTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyTagManagerSerializationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: + """Returns a fully-qualified taxonomy string.""" + return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + + @staticmethod + def parse_taxonomy_path(path: str) -> Dict[str,str]: + """Parses a taxonomy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerSerializationTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy tag manager serialization 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, PolicyTagManagerSerializationTransport]): 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, PolicyTagManagerSerializationTransport): + # transport is a PolicyTagManagerSerializationTransport 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=True, + ) + + def import_taxonomies(self, + request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ImportTaxonomiesResponse: + r"""Imports all taxonomies and their policy tags to a + project as new taxonomies. + + This method provides a bulk taxonomy / policy tag + creation using nested proto structure. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ImportTaxonomiesRequest, dict]): + The request object. Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.ImportTaxonomiesResponse: + Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a policytagmanagerserialization.ImportTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanagerserialization.ImportTaxonomiesRequest): + request = policytagmanagerserialization.ImportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_taxonomies] + + # 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 export_taxonomies(self, + request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policytagmanagerserialization.ExportTaxonomiesResponse: + r"""Exports all taxonomies and their policy tags in a + project. + This method generates SerializedTaxonomy protos with + nested policy tags that can be used as an input for + future ImportTaxonomies calls. + + Args: + request (Union[google.cloud.datacatalog_v1beta1.types.ExportTaxonomiesRequest, dict]): + The request object. Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.datacatalog_v1beta1.types.ExportTaxonomiesResponse: + Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a policytagmanagerserialization.ExportTaxonomiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policytagmanagerserialization.ExportTaxonomiesRequest): + request = policytagmanagerserialization.ExportTaxonomiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_taxonomies] + + # 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-datacatalog", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PolicyTagManagerSerializationClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py new file mode 100644 index 00000000..2864dab0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/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 PolicyTagManagerSerializationTransport +from .grpc import PolicyTagManagerSerializationGrpcTransport +from .grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerSerializationTransport]] +_transport_registry['grpc'] = PolicyTagManagerSerializationGrpcTransport +_transport_registry['grpc_asyncio'] = PolicyTagManagerSerializationGrpcAsyncIOTransport + +__all__ = ( + 'PolicyTagManagerSerializationTransport', + 'PolicyTagManagerSerializationGrpcTransport', + 'PolicyTagManagerSerializationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py new file mode 100644 index 00000000..42853f2b --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py @@ -0,0 +1,160 @@ +# -*- 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 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.datacatalog_v1beta1.types import policytagmanagerserialization + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-datacatalog', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class PolicyTagManagerSerializationTransport(abc.ABC): + """Abstract transport class for PolicyTagManagerSerialization.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.import_taxonomies: gapic_v1.method.wrap_method( + self.import_taxonomies, + default_timeout=None, + client_info=client_info, + ), + self.export_taxonomies: gapic_v1.method.wrap_method( + self.export_taxonomies, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + Union[ + policytagmanagerserialization.ImportTaxonomiesResponse, + Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse] + ]]: + raise NotImplementedError() + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + Union[ + policytagmanagerserialization.ExportTaxonomiesResponse, + Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PolicyTagManagerSerializationTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py new file mode 100644 index 00000000..0fd74180 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py @@ -0,0 +1,290 @@ +# -*- 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.datacatalog_v1beta1.types import policytagmanagerserialization +from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO + + +class PolicyTagManagerSerializationGrpcTransport(PolicyTagManagerSerializationTransport): + """gRPC backend transport for PolicyTagManagerSerialization. + + Policy tag manager serialization API service allows clients + to manipulate their taxonomies and policy tags data with + serialized format. + + 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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'datacatalog.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 import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + policytagmanagerserialization.ImportTaxonomiesResponse]: + r"""Return a callable for the import taxonomies method over gRPC. + + Imports all taxonomies and their policy tags to a + project as new taxonomies. + + This method provides a bulk taxonomy / policy tag + creation using nested proto structure. + + Returns: + Callable[[~.ImportTaxonomiesRequest], + ~.ImportTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_taxonomies' not in self._stubs: + self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ImportTaxonomies', + request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, + ) + return self._stubs['import_taxonomies'] + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + policytagmanagerserialization.ExportTaxonomiesResponse]: + r"""Return a callable for the export taxonomies method over gRPC. + + Exports all taxonomies and their policy tags in a + project. + This method generates SerializedTaxonomy protos with + nested policy tags that can be used as an input for + future ImportTaxonomies calls. + + Returns: + Callable[[~.ExportTaxonomiesRequest], + ~.ExportTaxonomiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_taxonomies' not in self._stubs: + self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ExportTaxonomies', + request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, + ) + return self._stubs['export_taxonomies'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'PolicyTagManagerSerializationGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py new file mode 100644 index 00000000..d983db3f --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py @@ -0,0 +1,294 @@ +# -*- 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 grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization +from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO +from .grpc import PolicyTagManagerSerializationGrpcTransport + + +class PolicyTagManagerSerializationGrpcAsyncIOTransport(PolicyTagManagerSerializationTransport): + """gRPC AsyncIO backend transport for PolicyTagManagerSerialization. + + Policy tag manager serialization API service allows clients + to manipulate their taxonomies and policy tags data with + serialized format. + + 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 import_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ImportTaxonomiesRequest], + Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse]]: + r"""Return a callable for the import taxonomies method over gRPC. + + Imports all taxonomies and their policy tags to a + project as new taxonomies. + + This method provides a bulk taxonomy / policy tag + creation using nested proto structure. + + Returns: + Callable[[~.ImportTaxonomiesRequest], + Awaitable[~.ImportTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_taxonomies' not in self._stubs: + self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ImportTaxonomies', + request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, + ) + return self._stubs['import_taxonomies'] + + @property + def export_taxonomies(self) -> Callable[ + [policytagmanagerserialization.ExportTaxonomiesRequest], + Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse]]: + r"""Return a callable for the export taxonomies method over gRPC. + + Exports all taxonomies and their policy tags in a + project. + This method generates SerializedTaxonomy protos with + nested policy tags that can be used as an input for + future ImportTaxonomies calls. + + Returns: + Callable[[~.ExportTaxonomiesRequest], + Awaitable[~.ExportTaxonomiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_taxonomies' not in self._stubs: + self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( + '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ExportTaxonomies', + request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, + response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, + ) + return self._stubs['export_taxonomies'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PolicyTagManagerSerializationGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py new file mode 100644 index 00000000..1f5276b8 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py @@ -0,0 +1,175 @@ +# -*- 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 .datacatalog import ( + CreateEntryGroupRequest, + CreateEntryRequest, + CreateTagRequest, + CreateTagTemplateFieldRequest, + CreateTagTemplateRequest, + DeleteEntryGroupRequest, + DeleteEntryRequest, + DeleteTagRequest, + DeleteTagTemplateFieldRequest, + DeleteTagTemplateRequest, + Entry, + EntryGroup, + GetEntryGroupRequest, + GetEntryRequest, + GetTagTemplateRequest, + ListEntriesRequest, + ListEntriesResponse, + ListEntryGroupsRequest, + ListEntryGroupsResponse, + ListTagsRequest, + ListTagsResponse, + LookupEntryRequest, + RenameTagTemplateFieldRequest, + SearchCatalogRequest, + SearchCatalogResponse, + UpdateEntryGroupRequest, + UpdateEntryRequest, + UpdateTagRequest, + UpdateTagTemplateFieldRequest, + UpdateTagTemplateRequest, + EntryType, +) +from .gcs_fileset_spec import ( + GcsFilesetSpec, + GcsFileSpec, +) +from .policytagmanager import ( + CreatePolicyTagRequest, + CreateTaxonomyRequest, + DeletePolicyTagRequest, + DeleteTaxonomyRequest, + GetPolicyTagRequest, + GetTaxonomyRequest, + ListPolicyTagsRequest, + ListPolicyTagsResponse, + ListTaxonomiesRequest, + ListTaxonomiesResponse, + PolicyTag, + Taxonomy, + UpdatePolicyTagRequest, + UpdateTaxonomyRequest, +) +from .policytagmanagerserialization import ( + ExportTaxonomiesRequest, + ExportTaxonomiesResponse, + ImportTaxonomiesRequest, + ImportTaxonomiesResponse, + InlineSource, + SerializedPolicyTag, + SerializedTaxonomy, +) +from .schema import ( + ColumnSchema, + Schema, +) +from .search import ( + SearchCatalogResult, + SearchResultType, +) +from .table_spec import ( + BigQueryDateShardedSpec, + BigQueryTableSpec, + TableSpec, + ViewSpec, + TableSourceType, +) +from .tags import ( + FieldType, + Tag, + TagField, + TagTemplate, + TagTemplateField, +) +from .timestamps import ( + SystemTimestamps, +) + +__all__ = ( + 'IntegratedSystem', + 'CreateEntryGroupRequest', + 'CreateEntryRequest', + 'CreateTagRequest', + 'CreateTagTemplateFieldRequest', + 'CreateTagTemplateRequest', + 'DeleteEntryGroupRequest', + 'DeleteEntryRequest', + 'DeleteTagRequest', + 'DeleteTagTemplateFieldRequest', + 'DeleteTagTemplateRequest', + 'Entry', + 'EntryGroup', + 'GetEntryGroupRequest', + 'GetEntryRequest', + 'GetTagTemplateRequest', + 'ListEntriesRequest', + 'ListEntriesResponse', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'ListTagsRequest', + 'ListTagsResponse', + 'LookupEntryRequest', + 'RenameTagTemplateFieldRequest', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'UpdateEntryGroupRequest', + 'UpdateEntryRequest', + 'UpdateTagRequest', + 'UpdateTagTemplateFieldRequest', + 'UpdateTagTemplateRequest', + 'EntryType', + 'GcsFilesetSpec', + 'GcsFileSpec', + 'CreatePolicyTagRequest', + 'CreateTaxonomyRequest', + 'DeletePolicyTagRequest', + 'DeleteTaxonomyRequest', + 'GetPolicyTagRequest', + 'GetTaxonomyRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'PolicyTag', + 'Taxonomy', + 'UpdatePolicyTagRequest', + 'UpdateTaxonomyRequest', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + 'ImportTaxonomiesRequest', + 'ImportTaxonomiesResponse', + 'InlineSource', + 'SerializedPolicyTag', + 'SerializedTaxonomy', + 'ColumnSchema', + 'Schema', + 'SearchCatalogResult', + 'SearchResultType', + 'BigQueryDateShardedSpec', + 'BigQueryTableSpec', + 'TableSpec', + 'ViewSpec', + 'TableSourceType', + 'FieldType', + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'SystemTimestamps', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py new file mode 100644 index 00000000..8d0def72 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py @@ -0,0 +1,36 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'IntegratedSystem', + }, +) + + +class IntegratedSystem(proto.Enum): + r"""This enum describes all the possible systems that Data + Catalog integrates with. + """ + INTEGRATED_SYSTEM_UNSPECIFIED = 0 + BIGQUERY = 1 + CLOUD_PUBSUB = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py new file mode 100644 index 00000000..9b3cf03e --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py @@ -0,0 +1,1225 @@ +# -*- 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.datacatalog_v1beta1.types import common +from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec as gcd_gcs_fileset_spec +from google.cloud.datacatalog_v1beta1.types import schema as gcd_schema +from google.cloud.datacatalog_v1beta1.types import search +from google.cloud.datacatalog_v1beta1.types import table_spec +from google.cloud.datacatalog_v1beta1.types import tags as gcd_tags +from google.cloud.datacatalog_v1beta1.types import timestamps +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'EntryType', + 'SearchCatalogRequest', + 'SearchCatalogResponse', + 'CreateEntryGroupRequest', + 'UpdateEntryGroupRequest', + 'GetEntryGroupRequest', + 'DeleteEntryGroupRequest', + 'ListEntryGroupsRequest', + 'ListEntryGroupsResponse', + 'CreateEntryRequest', + 'UpdateEntryRequest', + 'DeleteEntryRequest', + 'GetEntryRequest', + 'LookupEntryRequest', + 'Entry', + 'EntryGroup', + 'CreateTagTemplateRequest', + 'GetTagTemplateRequest', + 'UpdateTagTemplateRequest', + 'DeleteTagTemplateRequest', + 'CreateTagRequest', + 'UpdateTagRequest', + 'DeleteTagRequest', + 'CreateTagTemplateFieldRequest', + 'UpdateTagTemplateFieldRequest', + 'RenameTagTemplateFieldRequest', + 'DeleteTagTemplateFieldRequest', + 'ListTagsRequest', + 'ListTagsResponse', + 'ListEntriesRequest', + 'ListEntriesResponse', + }, +) + + +class EntryType(proto.Enum): + r"""Entry resources in Data Catalog can be of different types e.g. a + BigQuery Table entry is of type ``TABLE``. This enum describes all + the possible types Data Catalog contains. + """ + ENTRY_TYPE_UNSPECIFIED = 0 + TABLE = 2 + MODEL = 5 + DATA_STREAM = 3 + FILESET = 4 + + +class SearchCatalogRequest(proto.Message): + r"""Request message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + + Attributes: + scope (google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope): + Required. The scope of this search request. A ``scope`` that + has empty ``include_org_ids``, ``include_project_ids`` AND + false ``include_gcp_public_datasets`` is considered invalid. + Data Catalog will return an error in such a case. + query (str): + Required. The query string in search query syntax. The query + must be non-empty. + + Query strings can be simple as "x" or more qualified as: + + - name:x + - column:x + - description:y + + Note: Query tokens need to have a minimum of 3 characters + for substring matching to work correctly. See `Data Catalog + Search + Syntax `__ + for more information. + page_size (int): + Number of results in the search page. If <=0 then defaults + to 10. Max limit for page_size is 1000. Throws an invalid + argument for page_size > 1000. + page_token (str): + Optional. Pagination token returned in an earlier + [SearchCatalogResponse.next_page_token][google.cloud.datacatalog.v1beta1.SearchCatalogResponse.next_page_token], + which indicates that this is a continuation of a prior + [SearchCatalogRequest][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog] + call, and that the system should return the next page of + data. If empty, the first page is returned. + order_by (str): + Specifies the ordering of results, currently supported + case-sensitive choices are: + + - ``relevance``, only supports descending + - ``last_modified_timestamp [asc|desc]``, defaults to + descending if not specified + + If not specified, defaults to ``relevance`` descending. + """ + + class Scope(proto.Message): + r"""The criteria that select the subspace used for query + matching. + + Attributes: + include_org_ids (Sequence[str]): + The list of organization IDs to search + within. To find your organization ID, follow + instructions in + https://cloud.google.com/resource- + manager/docs/creating-managing-organization. + include_project_ids (Sequence[str]): + The list of project IDs to search within. To + learn more about the distinction between project + names/IDs/numbers, go to + https://cloud.google.com/docs/overview/#projects. + include_gcp_public_datasets (bool): + If ``true``, include Google Cloud Platform (GCP) public + datasets in the search results. Info on GCP public datasets + is available at https://cloud.google.com/public-datasets/. + By default, GCP public datasets are excluded. + """ + + include_org_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + include_project_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + include_gcp_public_datasets = proto.Field( + proto.BOOL, + number=7, + ) + + scope = proto.Field( + proto.MESSAGE, + number=6, + message=Scope, + ) + query = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class SearchCatalogResponse(proto.Message): + r"""Response message for + [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. + + Attributes: + results (Sequence[google.cloud.datacatalog_v1beta1.types.SearchCatalogResult]): + Search results. + next_page_token (str): + The token that can be used to retrieve the + next page of results. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=search.SearchCatalogResult, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateEntryGroupRequest(proto.Message): + r"""Request message for + [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. + + Attributes: + parent (str): + Required. The name of the project this entry group is in. + Example: + + - projects/{project_id}/locations/{location} + + Note that this EntryGroup and its child resources may not + actually be stored in the location in this name. + entry_group_id (str): + Required. The id of the entry group to + create. The id must begin with a letter or + underscore, contain only English letters, + numbers and underscores, and be at most 64 + characters. + entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): + The entry group to create. Defaults to an + empty entry group. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entry_group_id = proto.Field( + proto.STRING, + number=3, + ) + entry_group = proto.Field( + proto.MESSAGE, + number=2, + message='EntryGroup', + ) + + +class UpdateEntryGroupRequest(proto.Message): + r"""Request message for + [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. + + Attributes: + entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): + Required. The updated entry group. "name" + field must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the entry group. If + absent or empty, all modifiable fields are + updated. + """ + + entry_group = proto.Field( + proto.MESSAGE, + number=1, + message='EntryGroup', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEntryGroupRequest(proto.Message): + r"""Request message for + [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. + + Attributes: + name (str): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return. If not set or empty, + all fields are returned. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntryGroupRequest(proto.Message): + r"""Request message for + [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. + + Attributes: + name (str): + Required. The name of the entry group. For example, + ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. + force (bool): + Optional. If true, deletes all entries in the + entry group. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListEntryGroupsRequest(proto.Message): + r"""Request message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + + Attributes: + parent (str): + Required. The name of the location that contains the entry + groups, which can be provided in URL format. Example: + + - projects/{project_id}/locations/{location} + page_size (int): + Optional. The maximum number of items to return. Default is + 10. Max limit is 1000. Throws an invalid argument for + ``page_size > 1000``. + page_token (str): + Optional. Token that specifies which page is + requested. If empty, the first page is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEntryGroupsResponse(proto.Message): + r"""Response message for + [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. + + Attributes: + entry_groups (Sequence[google.cloud.datacatalog_v1beta1.types.EntryGroup]): + EntryGroup details. + next_page_token (str): + Token to retrieve the next page of results. + It is set to empty if no items remain in + results. + """ + + @property + def raw_page(self): + return self + + entry_groups = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntryGroup', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEntryRequest(proto.Message): + r"""Request message for + [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. + + Attributes: + parent (str): + Required. The name of the entry group this entry is in. + Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + + Note that this Entry and its child resources may not + actually be stored in the location in this name. + entry_id (str): + Required. The id of the entry to create. + entry (google.cloud.datacatalog_v1beta1.types.Entry): + Required. The entry to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entry_id = proto.Field( + proto.STRING, + number=3, + ) + entry = proto.Field( + proto.MESSAGE, + number=2, + message='Entry', + ) + + +class UpdateEntryRequest(proto.Message): + r"""Request message for + [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. + + Attributes: + entry (google.cloud.datacatalog_v1beta1.types.Entry): + Required. The updated entry. The "name" field + must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the entry. If absent or empty, all + modifiable fields are updated. + + The following fields are modifiable: + + - For entries with type ``DATA_STREAM``: + + - ``schema`` + + - For entries with type ``FILESET`` + + - ``schema`` + - ``display_name`` + - ``description`` + - ``gcs_fileset_spec`` + - ``gcs_fileset_spec.file_patterns`` + + - For entries with ``user_specified_type`` + + - ``schema`` + - ``display_name`` + - ``description`` + - user_specified_type + - user_specified_system + - linked_resource + - source_system_timestamps + """ + + entry = proto.Field( + proto.MESSAGE, + number=1, + message='Entry', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntryRequest(proto.Message): + r"""Request message for + [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. + + Attributes: + name (str): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEntryRequest(proto.Message): + r"""Request message for + [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. + + Attributes: + name (str): + Required. The name of the entry. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LookupEntryRequest(proto.Message): + r"""Request message for + [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + linked_resource (str): + The full name of the Google Cloud Platform resource the Data + Catalog entry represents. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name. + Full names are case-sensitive. + + Examples: + + - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId + - //pubsub.googleapis.com/projects/projectId/topics/topicId + This field is a member of `oneof`_ ``target_name``. + sql_resource (str): + The SQL name of the entry. SQL names are case-sensitive. + + Examples: + + - ``pubsub.project_id.topic_id`` + - :literal:`pubsub.project_id.`topic.id.with.dots\`` + - ``bigquery.table.project_id.dataset_id.table_id`` + - ``bigquery.dataset.project_id.dataset_id`` + - ``datacatalog.entry.project_id.location_id.entry_group_id.entry_id`` + + ``*_id``\ s shoud satisfy the standard SQL rules for + identifiers. + https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. + This field is a member of `oneof`_ ``target_name``. + """ + + linked_resource = proto.Field( + proto.STRING, + number=1, + oneof='target_name', + ) + sql_resource = proto.Field( + proto.STRING, + number=3, + oneof='target_name', + ) + + +class Entry(proto.Message): + r"""Entry Metadata. A Data Catalog Entry resource represents another + resource in Google Cloud Platform (such as a BigQuery dataset or a + Pub/Sub topic), or outside of Google Cloud Platform. Clients can use + the ``linked_resource`` field in the Entry resource to refer to the + original resource ID of the source system. + + An Entry resource contains resource details, such as its schema. An + Entry can also be used to attach flexible metadata, such as a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The Data Catalog resource name of the entry in URL format. + Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + + Note that this Entry and its child resources may not + actually be stored in the location in this name. + linked_resource (str): + The resource this metadata entry refers to. + + For Google Cloud Platform resources, ``linked_resource`` is + the `full name of the + resource `__. + For example, the ``linked_resource`` for a table resource + from BigQuery is: + + - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId + + Output only when Entry is of type in the EntryType enum. For + entries with user_specified_type, this field is optional and + defaults to an empty string. + type_ (google.cloud.datacatalog_v1beta1.types.EntryType): + The type of the entry. + Only used for Entries with types in the + EntryType enum. + This field is a member of `oneof`_ ``entry_type``. + user_specified_type (str): + Entry type if it does not fit any of the input-allowed + values listed in ``EntryType`` enum above. When creating an + entry, users should check the enum values first, if nothing + matches the entry to be created, then provide a custom + value, for example "my_special_type". + ``user_specified_type`` strings must begin with a letter or + underscore and can only contain letters, numbers, and + underscores; are case insensitive; must be at least 1 + character and at most 64 characters long. + + Currently, only FILESET enum value is allowed. All other + entries created through Data Catalog must use + ``user_specified_type``. + This field is a member of `oneof`_ ``entry_type``. + integrated_system (google.cloud.datacatalog_v1beta1.types.IntegratedSystem): + Output only. This field indicates the entry's + source system that Data Catalog integrates with, + such as BigQuery or Pub/Sub. + This field is a member of `oneof`_ ``system``. + user_specified_system (str): + This field indicates the entry's source system that Data + Catalog does not integrate with. ``user_specified_system`` + strings must begin with a letter or underscore and can only + contain letters, numbers, and underscores; are case + insensitive; must be at least 1 character and at most 64 + characters long. + This field is a member of `oneof`_ ``system``. + gcs_fileset_spec (google.cloud.datacatalog_v1beta1.types.GcsFilesetSpec): + Specification that applies to a Cloud Storage + fileset. This is only valid on entries of type + FILESET. + This field is a member of `oneof`_ ``type_spec``. + bigquery_table_spec (google.cloud.datacatalog_v1beta1.types.BigQueryTableSpec): + Specification that applies to a BigQuery table. This is only + valid on entries of type ``TABLE``. + This field is a member of `oneof`_ ``type_spec``. + bigquery_date_sharded_spec (google.cloud.datacatalog_v1beta1.types.BigQueryDateShardedSpec): + Specification for a group of BigQuery tables with name + pattern ``[prefix]YYYYMMDD``. Context: + https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. + This field is a member of `oneof`_ ``type_spec``. + display_name (str): + Display information such as title and + description. A short name to identify the entry, + for example, "Analytics Data - Jan 2011". + Default value is an empty string. + description (str): + Entry description, which can consist of + several sentences or paragraphs that describe + entry contents. Default value is an empty + string. + schema (google.cloud.datacatalog_v1beta1.types.Schema): + Schema of the entry. An entry might not have + any schema attached to it. + source_system_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): + Output only. Timestamps about the underlying resource, not + about this Data Catalog entry. Output only when Entry is of + type in the EntryType enum. For entries with + user_specified_type, this field is optional and defaults to + an empty timestamp. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + linked_resource = proto.Field( + proto.STRING, + number=9, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + oneof='entry_type', + enum='EntryType', + ) + user_specified_type = proto.Field( + proto.STRING, + number=16, + oneof='entry_type', + ) + integrated_system = proto.Field( + proto.ENUM, + number=17, + oneof='system', + enum=common.IntegratedSystem, + ) + user_specified_system = proto.Field( + proto.STRING, + number=18, + oneof='system', + ) + gcs_fileset_spec = proto.Field( + proto.MESSAGE, + number=6, + oneof='type_spec', + message=gcd_gcs_fileset_spec.GcsFilesetSpec, + ) + bigquery_table_spec = proto.Field( + proto.MESSAGE, + number=12, + oneof='type_spec', + message=table_spec.BigQueryTableSpec, + ) + bigquery_date_sharded_spec = proto.Field( + proto.MESSAGE, + number=15, + oneof='type_spec', + message=table_spec.BigQueryDateShardedSpec, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + schema = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_schema.Schema, + ) + source_system_timestamps = proto.Field( + proto.MESSAGE, + number=7, + message=timestamps.SystemTimestamps, + ) + + +class EntryGroup(proto.Message): + r"""EntryGroup Metadata. An EntryGroup resource represents a logical + grouping of zero or more Data Catalog + [Entry][google.cloud.datacatalog.v1beta1.Entry] resources. + + Attributes: + name (str): + The resource name of the entry group in URL format. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + + Note that this EntryGroup and its child resources may not + actually be stored in the location in this name. + display_name (str): + A short name to identify the entry group, for + example, "analytics data - jan 2011". Default + value is an empty string. + description (str): + Entry group description, which can consist of + several sentences or paragraphs that describe + entry group contents. Default value is an empty + string. + data_catalog_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): + Output only. Timestamps about this + EntryGroup. Default value is empty timestamps. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + data_catalog_timestamps = proto.Field( + proto.MESSAGE, + number=4, + message=timestamps.SystemTimestamps, + ) + + +class CreateTagTemplateRequest(proto.Message): + r"""Request message for + [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. + + Attributes: + parent (str): + Required. The name of the project and the template location + [region](https://cloud.google.com/data-catalog/docs/concepts/regions. + + Example: + + - projects/{project_id}/locations/us-central1 + tag_template_id (str): + Required. The id of the tag template to + create. + tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): + Required. The tag template to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag_template_id = proto.Field( + proto.STRING, + number=3, + ) + tag_template = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.TagTemplate, + ) + + +class GetTagTemplateRequest(proto.Message): + r"""Request message for + [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. + + Attributes: + name (str): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTagTemplateRequest(proto.Message): + r"""Request message for + [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. + + Attributes: + tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): + Required. The template to update. The "name" + field must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The field mask specifies the parts of the template to + overwrite. + + Allowed fields: + + - ``display_name`` + + If absent or empty, all of the allowed fields above will be + updated. + """ + + tag_template = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_tags.TagTemplate, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteTagTemplateRequest(proto.Message): + r"""Request message for + [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. + + Attributes: + name (str): + Required. The name of the tag template to delete. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + force (bool): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of any possible tags + using this template. ``force = false`` will be supported in + the future. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class CreateTagRequest(proto.Message): + r"""Request message for + [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. + + Attributes: + parent (str): + Required. The name of the resource to attach this tag to. + Tags can be attached to Entries. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + + Note that this Tag and its child resources may not actually + be stored in the location in this name. + tag (google.cloud.datacatalog_v1beta1.types.Tag): + Required. The tag to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.Tag, + ) + + +class UpdateTagRequest(proto.Message): + r"""Request message for + [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. + + Attributes: + tag (google.cloud.datacatalog_v1beta1.types.Tag): + Required. The updated tag. The "name" field + must be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update on the Tag. If absent or empty, all + modifiable fields are updated. Currently the only modifiable + field is the field ``fields``. + """ + + tag = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_tags.Tag, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteTagRequest(proto.Message): + r"""Request message for + [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. + + Attributes: + name (str): + Required. The name of the tag to delete. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTagTemplateFieldRequest(proto.Message): + r"""Request message for + [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. + + Attributes: + parent (str): + Required. The name of the project and the template location + `region `__. + + Example: + + - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} + tag_template_field_id (str): + Required. The ID of the tag template field to create. Field + ids can contain letters (both uppercase and lowercase), + numbers (0-9), underscores (_) and dashes (-). Field IDs + must be at least 1 character long and at most 128 characters + long. Field IDs must also be unique within their template. + tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): + Required. The tag template field to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + tag_template_field_id = proto.Field( + proto.STRING, + number=2, + ) + tag_template_field = proto.Field( + proto.MESSAGE, + number=3, + message=gcd_tags.TagTemplateField, + ) + + +class UpdateTagTemplateFieldRequest(proto.Message): + r"""Request message for + [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template field. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): + Required. The template to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The field mask specifies the parts of the template + to be updated. Allowed fields: + + - ``display_name`` + - ``type.enum_type`` + - ``is_required`` + + If ``update_mask`` is not set or empty, all of the allowed + fields above will be updated. + + When updating an enum type, the provided values will be + merged with the existing values. Therefore, enum values can + only be added, existing enum values cannot be deleted nor + renamed. Updating a template field from optional to required + is NOT allowed. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + tag_template_field = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tags.TagTemplateField, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class RenameTagTemplateFieldRequest(proto.Message): + r"""Request message for + [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + new_tag_template_field_id (str): + Required. The new ID of this tag template field. For + example, ``my_new_field``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + new_tag_template_field_id = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteTagTemplateFieldRequest(proto.Message): + r"""Request message for + [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. + + Attributes: + name (str): + Required. The name of the tag template field to delete. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} + force (bool): + Required. Currently, this field must always be set to + ``true``. This confirms the deletion of this field from any + tags using this field. ``force = false`` will be supported + in the future. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListTagsRequest(proto.Message): + r"""Request message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + + Attributes: + parent (str): + Required. The name of the Data Catalog resource to list the + tags of. The resource could be an + [Entry][google.cloud.datacatalog.v1beta1.Entry] or an + [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. + + Examples: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} + page_size (int): + The maximum number of tags to return. Default + is 10. Max limit is 1000. + page_token (str): + Token that specifies which page is requested. + If empty, the first page is returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTagsResponse(proto.Message): + r"""Response message for + [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. + + Attributes: + tags (Sequence[google.cloud.datacatalog_v1beta1.types.Tag]): + [Tag][google.cloud.datacatalog.v1beta1.Tag] details. + next_page_token (str): + Token to retrieve the next page of results. + It is set to empty if no items remain in + results. + """ + + @property + def raw_page(self): + return self + + tags = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_tags.Tag, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEntriesRequest(proto.Message): + r"""Request message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + + Attributes: + parent (str): + Required. The name of the entry group that contains the + entries, which can be provided in URL format. Example: + + - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} + page_size (int): + The maximum number of items to return. Default is 10. Max + limit is 1000. Throws an invalid argument for + ``page_size > 1000``. + page_token (str): + Token that specifies which page is requested. + If empty, the first page is returned. + read_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to return for each Entry. If not set or empty, + all fields are returned. For example, setting read_mask to + contain only one path "name" will cause ListEntries to + return a list of Entries with only "name" field. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + read_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class ListEntriesResponse(proto.Message): + r"""Response message for + [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. + + Attributes: + entries (Sequence[google.cloud.datacatalog_v1beta1.types.Entry]): + Entry details. + next_page_token (str): + Token to retrieve the next page of results. + It is set to empty if no items remain in + results. + """ + + @property + def raw_page(self): + return self + + entries = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Entry', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py new file mode 100644 index 00000000..713fc6c2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py @@ -0,0 +1,113 @@ +# -*- 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.datacatalog_v1beta1.types import timestamps + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'GcsFilesetSpec', + 'GcsFileSpec', + }, +) + + +class GcsFilesetSpec(proto.Message): + r"""Describes a Cloud Storage fileset entry. + + Attributes: + file_patterns (Sequence[str]): + Required. Patterns to identify a set of files in Google + Cloud Storage. See `Cloud Storage + documentation `__ + for more information. Note that bucket wildcards are + currently not supported. + + Examples of valid file_patterns: + + - ``gs://bucket_name/dir/*``: matches all files within + ``bucket_name/dir`` directory. + - ``gs://bucket_name/dir/**``: matches all files in + ``bucket_name/dir`` spanning all subdirectories. + - ``gs://bucket_name/file*``: matches files prefixed by + ``file`` in ``bucket_name`` + - ``gs://bucket_name/??.txt``: matches files with two + characters followed by ``.txt`` in ``bucket_name`` + - ``gs://bucket_name/[aeiou].txt``: matches files that + contain a single vowel character followed by ``.txt`` in + ``bucket_name`` + - ``gs://bucket_name/[a-m].txt``: matches files that + contain ``a``, ``b``, ... or ``m`` followed by ``.txt`` + in ``bucket_name`` + - ``gs://bucket_name/a/*/b``: matches all files in + ``bucket_name`` that match ``a/*/b`` pattern, such as + ``a/c/b``, ``a/d/b`` + - ``gs://another_bucket/a.txt``: matches + ``gs://another_bucket/a.txt`` + + You can combine wildcards to provide more powerful matches, + for example: + + - ``gs://bucket_name/[a-m]??.j*g`` + sample_gcs_file_specs (Sequence[google.cloud.datacatalog_v1beta1.types.GcsFileSpec]): + Output only. Sample files contained in this + fileset, not all files contained in this fileset + are represented here. + """ + + file_patterns = proto.RepeatedField( + proto.STRING, + number=1, + ) + sample_gcs_file_specs = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='GcsFileSpec', + ) + + +class GcsFileSpec(proto.Message): + r"""Specifications of a single file in Cloud Storage. + + Attributes: + file_path (str): + Required. The full file path. Example: + ``gs://bucket_name/a/b.txt``. + gcs_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): + Output only. Timestamps about the Cloud + Storage file. + size_bytes (int): + Output only. The size of the file, in bytes. + """ + + file_path = proto.Field( + proto.STRING, + number=1, + ) + gcs_timestamps = proto.Field( + proto.MESSAGE, + number=2, + message=timestamps.SystemTimestamps, + ) + size_bytes = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py new file mode 100644 index 00000000..1721e86c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py @@ -0,0 +1,449 @@ +# -*- 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 field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'Taxonomy', + 'PolicyTag', + 'CreateTaxonomyRequest', + 'DeleteTaxonomyRequest', + 'UpdateTaxonomyRequest', + 'ListTaxonomiesRequest', + 'ListTaxonomiesResponse', + 'GetTaxonomyRequest', + 'CreatePolicyTagRequest', + 'DeletePolicyTagRequest', + 'UpdatePolicyTagRequest', + 'ListPolicyTagsRequest', + 'ListPolicyTagsResponse', + 'GetPolicyTagRequest', + }, +) + + +class Taxonomy(proto.Message): + r"""A taxonomy is a collection of policy tags that classify data along a + common axis. For instance a data *sensitivity* taxonomy could + contain policy tags denoting PII such as age, zipcode, and SSN. A + data *origin* taxonomy could contain policy tags to distinguish user + data, employee data, partner data, public data. + + Attributes: + name (str): + Output only. Resource name of this taxonomy, whose format + is: + "projects/{project_number}/locations/{location_id}/taxonomies/{id}". + display_name (str): + Required. User defined name of this taxonomy. + It must: contain only unicode letters, numbers, + underscores, dashes and spaces; not start or end + with spaces; and be at most 200 bytes long when + encoded in UTF-8. + description (str): + Optional. Description of this taxonomy. It + must: contain only unicode characters, tabs, + newlines, carriage returns and page breaks; and + be at most 2000 bytes long when encoded in + UTF-8. If not set, defaults to an empty + description. + activated_policy_types (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy.PolicyType]): + Optional. A list of policy types that are + activated for this taxonomy. If not set, + defaults to an empty list. + """ + class PolicyType(proto.Enum): + r"""Defines policy types where policy tag can be used for.""" + POLICY_TYPE_UNSPECIFIED = 0 + FINE_GRAINED_ACCESS_CONTROL = 1 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + activated_policy_types = proto.RepeatedField( + proto.ENUM, + number=6, + enum=PolicyType, + ) + + +class PolicyTag(proto.Message): + r"""Denotes one policy tag in a taxonomy (e.g. ssn). Policy Tags + can be defined in a hierarchy. For example, consider the + following hierarchy: Geolocation -> (LatLong, City, ZipCode). + PolicyTag "Geolocation" contains three child policy tags: + "LatLong", "City", and "ZipCode". + + Attributes: + name (str): + Output only. Resource name of this policy tag, whose format + is: + "projects/{project_number}/locations/{location_id}/taxonomies/{taxonomy_id}/policyTags/{id}". + display_name (str): + Required. User defined name of this policy + tag. It must: be unique within the parent + taxonomy; contain only unicode letters, numbers, + underscores, dashes and spaces; not start or end + with spaces; and be at most 200 bytes long when + encoded in UTF-8. + description (str): + Description of this policy tag. It must: + contain only unicode characters, tabs, newlines, + carriage returns and page breaks; and be at most + 2000 bytes long when encoded in UTF-8. If not + set, defaults to an empty description. If not + set, defaults to an empty description. + parent_policy_tag (str): + Resource name of this policy tag's parent + policy tag (e.g. for the "LatLong" policy tag in + the example above, this field contains the + resource name of the "Geolocation" policy tag). + If empty, it means this policy tag is a top + level policy tag (e.g. this field is empty for + the "Geolocation" policy tag in the example + above). If not set, defaults to an empty string. + child_policy_tags (Sequence[str]): + Output only. Resource names of child policy + tags of this policy tag. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + parent_policy_tag = proto.Field( + proto.STRING, + number=4, + ) + child_policy_tags = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class CreateTaxonomyRequest(proto.Message): + r"""Request message for + [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. + + Attributes: + parent (str): + Required. Resource name of the project that + the taxonomy will belong to. + taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): + The taxonomy to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + taxonomy = proto.Field( + proto.MESSAGE, + number=2, + message='Taxonomy', + ) + + +class DeleteTaxonomyRequest(proto.Message): + r"""Request message for + [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. + + Attributes: + name (str): + Required. Resource name of the taxonomy to be + deleted. All policy tags in this taxonomy will + also be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTaxonomyRequest(proto.Message): + r"""Request message for + [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. + + Attributes: + taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): + The taxonomy to update. Only description, display_name, and + activated policy types can be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + If not set, defaults to all of the fields that are allowed + to update. + """ + + taxonomy = proto.Field( + proto.MESSAGE, + number=1, + message='Taxonomy', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListTaxonomiesRequest(proto.Message): + r"""Request message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + + Attributes: + parent (str): + Required. Resource name of the project to + list the taxonomies of. + page_size (int): + The maximum number of items to return. Must + be a value between 1 and 1000. If not set, + defaults to 50. + page_token (str): + The next_page_token value returned from a previous list + request, if any. If not set, defaults to an empty string. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTaxonomiesResponse(proto.Message): + r"""Response message for + [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy]): + Taxonomies that the project contains. + next_page_token (str): + Token used to retrieve the next page of + results, or empty if there are no more results + in the list. + """ + + @property + def raw_page(self): + return self + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Taxonomy', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTaxonomyRequest(proto.Message): + r"""Request message for + [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. + + Attributes: + name (str): + Required. Resource name of the requested + taxonomy. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePolicyTagRequest(proto.Message): + r"""Request message for + [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. + + Attributes: + parent (str): + Required. Resource name of the taxonomy that + the policy tag will belong to. + policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): + The policy tag to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + policy_tag = proto.Field( + proto.MESSAGE, + number=2, + message='PolicyTag', + ) + + +class DeletePolicyTagRequest(proto.Message): + r"""Request message for + [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. + + Attributes: + name (str): + Required. Resource name of the policy tag to + be deleted. All of its descendant policy tags + will also be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePolicyTagRequest(proto.Message): + r"""Request message for + [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. + + Attributes: + policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): + The policy tag to update. Only the description, + display_name, and parent_policy_tag fields can be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The update mask applies to the resource. Only display_name, + description and parent_policy_tag can be updated and thus + can be listed in the mask. If update_mask is not provided, + all allowed fields (i.e. display_name, description and + parent) will be updated. For more information including the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + If not set, defaults to all of the fields that are allowed + to update. + """ + + policy_tag = proto.Field( + proto.MESSAGE, + number=1, + message='PolicyTag', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListPolicyTagsRequest(proto.Message): + r"""Request message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + + Attributes: + parent (str): + Required. Resource name of the taxonomy to + list the policy tags of. + page_size (int): + The maximum number of items to return. Must + be a value between 1 and 1000. If not set, + defaults to 50. + page_token (str): + The next_page_token value returned from a previous List + request, if any. If not set, defaults to an empty string. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPolicyTagsResponse(proto.Message): + r"""Response message for + [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. + + Attributes: + policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.PolicyTag]): + The policy tags that are in the requested + taxonomy. + next_page_token (str): + Token used to retrieve the next page of + results, or empty if there are no more results + in the list. + """ + + @property + def raw_page(self): + return self + + policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PolicyTag', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPolicyTagRequest(proto.Message): + r"""Request message for + [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. + + Attributes: + name (str): + Required. Resource name of the requested + policy tag. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py new file mode 100644 index 00000000..efe0aefd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py @@ -0,0 +1,210 @@ +# -*- 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.datacatalog_v1beta1.types import policytagmanager + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'SerializedTaxonomy', + 'SerializedPolicyTag', + 'ImportTaxonomiesRequest', + 'InlineSource', + 'ImportTaxonomiesResponse', + 'ExportTaxonomiesRequest', + 'ExportTaxonomiesResponse', + }, +) + + +class SerializedTaxonomy(proto.Message): + r"""Message capturing a taxonomy and its policy tag hierarchy as + a nested proto. Used for taxonomy import/export and mutation. + + Attributes: + display_name (str): + Required. Display name of the taxonomy. Max + 200 bytes when encoded in UTF-8. + description (str): + Description of the serialized taxonomy. The + length of the description is limited to 2000 + bytes when encoded in UTF-8. If not set, + defaults to an empty description. + policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedPolicyTag]): + Top level policy tags associated with the + taxonomy if any. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='SerializedPolicyTag', + ) + + +class SerializedPolicyTag(proto.Message): + r"""Message representing one policy tag when exported as a nested + proto. + + Attributes: + display_name (str): + Required. Display name of the policy tag. Max + 200 bytes when encoded in UTF-8. + description (str): + Description of the serialized policy tag. The + length of the description is limited to 2000 + bytes when encoded in UTF-8. If not set, + defaults to an empty description. + child_policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedPolicyTag]): + Children of the policy tag if any. + """ + + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + child_policy_tags = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SerializedPolicyTag', + ) + + +class ImportTaxonomiesRequest(proto.Message): + r"""Request message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Resource name of project that the + newly created taxonomies will belong to. + inline_source (google.cloud.datacatalog_v1beta1.types.InlineSource): + Inline source used for taxonomies import + This field is a member of `oneof`_ ``source``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + inline_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='InlineSource', + ) + + +class InlineSource(proto.Message): + r"""Inline source used for taxonomies import. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedTaxonomy]): + Required. Taxonomies to be imported. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SerializedTaxonomy', + ) + + +class ImportTaxonomiesResponse(proto.Message): + r"""Response message for + [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy]): + Taxonomies that were imported. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=policytagmanager.Taxonomy, + ) + + +class ExportTaxonomiesRequest(proto.Message): + r"""Request message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Resource name of the project that + taxonomies to be exported will share. + taxonomies (Sequence[str]): + Required. Resource names of the taxonomies to + be exported. + serialized_taxonomies (bool): + Export taxonomies as serialized taxonomies. + This field is a member of `oneof`_ ``destination``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + taxonomies = proto.RepeatedField( + proto.STRING, + number=2, + ) + serialized_taxonomies = proto.Field( + proto.BOOL, + number=3, + oneof='destination', + ) + + +class ExportTaxonomiesResponse(proto.Message): + r"""Response message for + [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. + + Attributes: + taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedTaxonomy]): + List of taxonomies and policy tags in a tree + structure. + """ + + taxonomies = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SerializedTaxonomy', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py new file mode 100644 index 00000000..ebd9763d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py @@ -0,0 +1,89 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'Schema', + 'ColumnSchema', + }, +) + + +class Schema(proto.Message): + r"""Represents a schema (e.g. BigQuery, GoogleSQL, Avro schema). + + Attributes: + columns (Sequence[google.cloud.datacatalog_v1beta1.types.ColumnSchema]): + Required. Schema of columns. A maximum of + 10,000 columns and sub-columns can be specified. + """ + + columns = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ColumnSchema', + ) + + +class ColumnSchema(proto.Message): + r"""Representation of a column within a schema. Columns could be + nested inside other columns. + + Attributes: + column (str): + Required. Name of the column. + type_ (str): + Required. Type of the column. + description (str): + Optional. Description of the column. Default + value is an empty string. + mode (str): + Optional. A column's mode indicates whether the values in + this column are required, nullable, etc. Only ``NULLABLE``, + ``REQUIRED`` and ``REPEATED`` are supported. Default mode is + ``NULLABLE``. + subcolumns (Sequence[google.cloud.datacatalog_v1beta1.types.ColumnSchema]): + Optional. Schema of sub-columns. A column can + have zero or more sub-columns. + """ + + column = proto.Field( + proto.STRING, + number=6, + ) + type_ = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + mode = proto.Field( + proto.STRING, + number=3, + ) + subcolumns = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ColumnSchema', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py new file mode 100644 index 00000000..7ec09b85 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py @@ -0,0 +1,88 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'SearchResultType', + 'SearchCatalogResult', + }, +) + + +class SearchResultType(proto.Enum): + r"""The different types of resources that can be returned in + search. + """ + SEARCH_RESULT_TYPE_UNSPECIFIED = 0 + ENTRY = 1 + TAG_TEMPLATE = 2 + ENTRY_GROUP = 3 + + +class SearchCatalogResult(proto.Message): + r"""A result that appears in the response of a search request. + Each result captures details of one entry that matches the + search. + + Attributes: + search_result_type (google.cloud.datacatalog_v1beta1.types.SearchResultType): + Type of the search result. This field can be + used to determine which Get method to call to + fetch the full resource. + search_result_subtype (str): + Sub-type of the search result. This is a dot-delimited + description of the resource's full type, and is the same as + the value callers would provide in the "type" search facet. + Examples: ``entry.table``, ``entry.dataStream``, + ``tagTemplate``. + relative_resource_name (str): + The relative resource name of the resource in URL format. + Examples: + + - ``projects/{project_id}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}`` + - ``projects/{project_id}/tagTemplates/{tag_template_id}`` + linked_resource (str): + The full name of the cloud resource the entry belongs to. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name. + Example: + + - ``//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId`` + """ + + search_result_type = proto.Field( + proto.ENUM, + number=1, + enum='SearchResultType', + ) + search_result_subtype = proto.Field( + proto.STRING, + number=2, + ) + relative_resource_name = proto.Field( + proto.STRING, + number=3, + ) + linked_resource = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py new file mode 100644 index 00000000..3c903a50 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py @@ -0,0 +1,147 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'TableSourceType', + 'BigQueryTableSpec', + 'ViewSpec', + 'TableSpec', + 'BigQueryDateShardedSpec', + }, +) + + +class TableSourceType(proto.Enum): + r"""Table source type.""" + TABLE_SOURCE_TYPE_UNSPECIFIED = 0 + BIGQUERY_VIEW = 2 + BIGQUERY_TABLE = 5 + + +class BigQueryTableSpec(proto.Message): + r"""Describes a BigQuery table. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + table_source_type (google.cloud.datacatalog_v1beta1.types.TableSourceType): + Output only. The table source type. + view_spec (google.cloud.datacatalog_v1beta1.types.ViewSpec): + Table view specification. This field should only be + populated if ``table_source_type`` is ``BIGQUERY_VIEW``. + This field is a member of `oneof`_ ``type_spec``. + table_spec (google.cloud.datacatalog_v1beta1.types.TableSpec): + Spec of a BigQuery table. This field should only be + populated if ``table_source_type`` is ``BIGQUERY_TABLE``. + This field is a member of `oneof`_ ``type_spec``. + """ + + table_source_type = proto.Field( + proto.ENUM, + number=1, + enum='TableSourceType', + ) + view_spec = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_spec', + message='ViewSpec', + ) + table_spec = proto.Field( + proto.MESSAGE, + number=3, + oneof='type_spec', + message='TableSpec', + ) + + +class ViewSpec(proto.Message): + r"""Table view specification. + + Attributes: + view_query (str): + Output only. The query that defines the table + view. + """ + + view_query = proto.Field( + proto.STRING, + number=1, + ) + + +class TableSpec(proto.Message): + r"""Normal BigQuery table spec. + + Attributes: + grouped_entry (str): + Output only. If the table is a dated shard, i.e., with name + pattern ``[prefix]YYYYMMDD``, ``grouped_entry`` is the Data + Catalog resource name of the date sharded grouped entry, for + example, + ``projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}``. + Otherwise, ``grouped_entry`` is empty. + """ + + grouped_entry = proto.Field( + proto.STRING, + number=1, + ) + + +class BigQueryDateShardedSpec(proto.Message): + r"""Spec for a group of BigQuery tables with name pattern + ``[prefix]YYYYMMDD``. Context: + https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding + + Attributes: + dataset (str): + Output only. The Data Catalog resource name of the dataset + entry the current table belongs to, for example, + ``projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}``. + table_prefix (str): + Output only. The table name prefix of the shards. The name + of any given shard is ``[table_prefix]YYYYMMDD``, for + example, for shard ``MyTable20180101``, the ``table_prefix`` + is ``MyTable``. + shard_count (int): + Output only. Total number of shards. + """ + + dataset = proto.Field( + proto.STRING, + number=1, + ) + table_prefix = proto.Field( + proto.STRING, + number=2, + ) + shard_count = proto.Field( + proto.INT64, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py new file mode 100644 index 00000000..62076ed0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py @@ -0,0 +1,384 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'Tag', + 'TagField', + 'TagTemplate', + 'TagTemplateField', + 'FieldType', + }, +) + + +class Tag(proto.Message): + r"""Tags are used to attach custom metadata to Data Catalog resources. + Tags conform to the specifications within their tag template. + + See `Data Catalog + IAM `__ for + information on the permissions needed to create or view tags. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The resource name of the tag in URL format. Example: + + - projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id} + + where ``tag_id`` is a system-generated identifier. Note that + this Tag may not actually be stored in the location in this + name. + template (str): + Required. The resource name of the tag template that this + tag uses. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + + This field cannot be modified after creation. + template_display_name (str): + Output only. The display name of the tag + template. + column (str): + Resources like Entry can have schemas associated with them. + This scope allows users to attach tags to an individual + column based on that schema. + + For attaching a tag to a nested column, use ``.`` to + separate the column names. Example: + + - ``outer_column.inner_column`` + This field is a member of `oneof`_ ``scope``. + fields (Sequence[google.cloud.datacatalog_v1beta1.types.Tag.FieldsEntry]): + Required. This maps the ID of a tag field to + the value of and additional information about + that field. Valid field IDs are defined by the + tag's template. A tag must have at least 1 field + and at most 500 fields. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + template = proto.Field( + proto.STRING, + number=2, + ) + template_display_name = proto.Field( + proto.STRING, + number=5, + ) + column = proto.Field( + proto.STRING, + number=4, + oneof='scope', + ) + fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='TagField', + ) + + +class TagField(proto.Message): + r"""Contains the value and supporting information for a field within a + [Tag][google.cloud.datacatalog.v1beta1.Tag]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + Output only. The display name of this field. + double_value (float): + Holds the value for a tag field with double + type. + This field is a member of `oneof`_ ``kind``. + string_value (str): + Holds the value for a tag field with string + type. + This field is a member of `oneof`_ ``kind``. + bool_value (bool): + Holds the value for a tag field with boolean + type. + This field is a member of `oneof`_ ``kind``. + timestamp_value (google.protobuf.timestamp_pb2.Timestamp): + Holds the value for a tag field with + timestamp type. + This field is a member of `oneof`_ ``kind``. + enum_value (google.cloud.datacatalog_v1beta1.types.TagField.EnumValue): + Holds the value for a tag field with enum + type. This value must be one of the allowed + values in the definition of this enum. + This field is a member of `oneof`_ ``kind``. + order (int): + Output only. The order of this field with respect to other + fields in this tag. It can be set in + [Tag][google.cloud.datacatalog.v1beta1.TagTemplateField.order]. + For example, a higher value can indicate a more important + field. The value can be negative. Multiple fields can have + the same order, and field orders within a tag do not have to + be sequential. + """ + + class EnumValue(proto.Message): + r"""Holds an enum value. + + Attributes: + display_name (str): + The display name of the enum value. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + double_value = proto.Field( + proto.DOUBLE, + number=2, + oneof='kind', + ) + string_value = proto.Field( + proto.STRING, + number=3, + oneof='kind', + ) + bool_value = proto.Field( + proto.BOOL, + number=4, + oneof='kind', + ) + timestamp_value = proto.Field( + proto.MESSAGE, + number=5, + oneof='kind', + message=timestamp_pb2.Timestamp, + ) + enum_value = proto.Field( + proto.MESSAGE, + number=6, + oneof='kind', + message=EnumValue, + ) + order = proto.Field( + proto.INT32, + number=7, + ) + + +class TagTemplate(proto.Message): + r"""A tag template defines a tag, which can have one or more typed + fields. The template is used to create and attach the tag to GCP + resources. `Tag template + roles `__ + provide permissions to create, edit, and use the template. See, for + example, the `TagTemplate + User `__ + role, which includes permission to use the tag template to tag + resources. + + Attributes: + name (str): + The resource name of the tag template in URL format. + Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} + + Note that this TagTemplate and its child resources may not + actually be stored in the location in this name. + display_name (str): + The display name for this template. Defaults + to an empty string. + fields (Sequence[google.cloud.datacatalog_v1beta1.types.TagTemplate.FieldsEntry]): + Required. Map of tag template field IDs to the settings for + the field. This map is an exhaustive list of the allowed + fields. This map must contain at least one field and at most + 500 fields. + + The keys to this map are tag template field IDs. Field IDs + can contain letters (both uppercase and lowercase), numbers + (0-9) and underscores (_). Field IDs must be at least 1 + character long and at most 64 characters long. Field IDs + must start with a letter or underscore. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + fields = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='TagTemplateField', + ) + + +class TagTemplateField(proto.Message): + r"""The template for an individual field within a tag template. + + Attributes: + name (str): + Output only. The resource name of the tag template field in + URL format. Example: + + - projects/{project_id}/locations/{location}/tagTemplates/{tag_template}/fields/{field} + + Note that this TagTemplateField may not actually be stored + in the location in this name. + display_name (str): + The display name for this field. Defaults to + an empty string. + type_ (google.cloud.datacatalog_v1beta1.types.FieldType): + Required. The type of value this tag field + can contain. + is_required (bool): + Whether this is a required field. Defaults to + false. + order (int): + The order of this field with respect to other + fields in this tag template. A higher value + indicates a more important field. The value can + be negative. Multiple fields can have the same + order, and field orders within a tag do not have + to be sequential. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + display_name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.MESSAGE, + number=2, + message='FieldType', + ) + is_required = proto.Field( + proto.BOOL, + number=3, + ) + order = proto.Field( + proto.INT32, + number=5, + ) + + +class FieldType(proto.Message): + r""" + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + primitive_type (google.cloud.datacatalog_v1beta1.types.FieldType.PrimitiveType): + Represents primitive types - string, bool + etc. + This field is a member of `oneof`_ ``type_decl``. + enum_type (google.cloud.datacatalog_v1beta1.types.FieldType.EnumType): + Represents an enum type. + This field is a member of `oneof`_ ``type_decl``. + """ + class PrimitiveType(proto.Enum): + r"""""" + PRIMITIVE_TYPE_UNSPECIFIED = 0 + DOUBLE = 1 + STRING = 2 + BOOL = 3 + TIMESTAMP = 4 + + class EnumType(proto.Message): + r""" + + Attributes: + allowed_values (Sequence[google.cloud.datacatalog_v1beta1.types.FieldType.EnumType.EnumValue]): + Required on create; optional on update. The + set of allowed values for this enum. This set + must not be empty, the display names of the + values in this set must not be empty and the + display names of the values must be case- + insensitively unique within this set. Currently, + enum values can only be added to the list of + allowed values. Deletion and renaming of enum + values are not supported. Can have up to 500 + allowed values. + """ + + class EnumValue(proto.Message): + r""" + + Attributes: + display_name (str): + Required. The display name of the enum value. + Must not be an empty string. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + + allowed_values = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FieldType.EnumType.EnumValue', + ) + + primitive_type = proto.Field( + proto.ENUM, + number=1, + oneof='type_decl', + enum=PrimitiveType, + ) + enum_type = proto.Field( + proto.MESSAGE, + number=2, + oneof='type_decl', + message=EnumType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py new file mode 100644 index 00000000..fc53ac2c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py @@ -0,0 +1,63 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.datacatalog.v1beta1', + manifest={ + 'SystemTimestamps', + }, +) + + +class SystemTimestamps(proto.Message): + r"""Timestamps about this resource according to a particular + system. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the resource within the + given system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last-modified time of the resource within + the given system. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The expiration time of the + resource within the given system. Currently only + apllicable to BigQuery resources. + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 00000000..eb1e18c1 --- /dev/null +++ b/owl-bot-staging/v1beta1/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', '3.10']) +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/datacatalog_v1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.9') +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', '3.8', '3.9']) +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.9') +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/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py new file mode 100644 index 00000000..f67585cf --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py @@ -0,0 +1,214 @@ +#! /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 datacatalogCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_entry': ('parent', 'entry_id', 'entry', ), + 'create_entry_group': ('parent', 'entry_group_id', 'entry_group', ), + 'create_policy_tag': ('parent', 'policy_tag', ), + 'create_tag': ('parent', 'tag', ), + 'create_tag_template': ('parent', 'tag_template_id', 'tag_template', ), + 'create_tag_template_field': ('parent', 'tag_template_field_id', 'tag_template_field', ), + 'create_taxonomy': ('parent', 'taxonomy', ), + 'delete_entry': ('name', ), + 'delete_entry_group': ('name', 'force', ), + 'delete_policy_tag': ('name', ), + 'delete_tag': ('name', ), + 'delete_tag_template': ('name', 'force', ), + 'delete_tag_template_field': ('name', 'force', ), + 'delete_taxonomy': ('name', ), + 'export_taxonomies': ('parent', 'taxonomies', 'serialized_taxonomies', ), + 'get_entry': ('name', ), + 'get_entry_group': ('name', 'read_mask', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_policy_tag': ('name', ), + 'get_tag_template': ('name', ), + 'get_taxonomy': ('name', ), + 'import_taxonomies': ('parent', 'inline_source', ), + 'list_entries': ('parent', 'page_size', 'page_token', 'read_mask', ), + 'list_entry_groups': ('parent', 'page_size', 'page_token', ), + 'list_policy_tags': ('parent', 'page_size', 'page_token', ), + 'list_tags': ('parent', 'page_size', 'page_token', ), + 'list_taxonomies': ('parent', 'page_size', 'page_token', ), + 'lookup_entry': ('linked_resource', 'sql_resource', ), + 'rename_tag_template_field': ('name', 'new_tag_template_field_id', ), + 'search_catalog': ('scope', 'query', 'page_size', 'page_token', 'order_by', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_entry': ('entry', 'update_mask', ), + 'update_entry_group': ('entry_group', 'update_mask', ), + 'update_policy_tag': ('policy_tag', 'update_mask', ), + 'update_tag': ('tag', 'update_mask', ), + 'update_tag_template': ('tag_template', 'update_mask', ), + 'update_tag_template_field': ('name', 'tag_template_field', 'update_mask', ), + 'update_taxonomy': ('taxonomy', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=datacatalogCallTransformer(), +): + """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 datacatalog 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 00000000..f76df593 --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,55 @@ +# -*- 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-datacatalog', + 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.28.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.19.4', + 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', + ), + 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/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__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/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py new file mode 100644 index 00000000..50ad3e77 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py @@ -0,0 +1,8035 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1beta1.services.data_catalog import DataCatalogAsyncClient +from google.cloud.datacatalog_v1beta1.services.data_catalog import DataCatalogClient +from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers +from google.cloud.datacatalog_v1beta1.services.data_catalog import transports +from google.cloud.datacatalog_v1beta1.types import common +from google.cloud.datacatalog_v1beta1.types import datacatalog +from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec +from google.cloud.datacatalog_v1beta1.types import schema +from google.cloud.datacatalog_v1beta1.types import search +from google.cloud.datacatalog_v1beta1.types import table_spec +from google.cloud.datacatalog_v1beta1.types import tags +from google.cloud.datacatalog_v1beta1.types import timestamps +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataCatalogClient._get_default_mtls_endpoint(None) is None + assert DataCatalogClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataCatalogClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DataCatalogClient, + DataCatalogAsyncClient, +]) +def test_data_catalog_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataCatalogGrpcTransport, "grpc"), + (transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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", [ + DataCatalogClient, + DataCatalogAsyncClient, +]) +def test_data_catalog_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 == 'datacatalog.googleapis.com:443' + + +def test_data_catalog_client_get_transport_class(): + transport = DataCatalogClient.get_transport_class() + available_transports = [ + transports.DataCatalogGrpcTransport, + ] + assert transport in available_transports + + transport = DataCatalogClient.get_transport_class("grpc") + assert transport == transports.DataCatalogGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) +@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) +def test_data_catalog_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(DataCatalogClient, '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(DataCatalogClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "true"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "false"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) +@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_catalog_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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(transport=transport_name, 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", [ + (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), + (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_data_catalog_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(transport=transport_name, 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_catalog_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataCatalogClient( + 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_search_catalog(transport: str = 'grpc', request_type=datacatalog.SearchCatalogRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse( + next_page_token='next_page_token_value', + ) + response = client.search_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_catalog_from_dict(): + test_search_catalog(request_type=dict) + + +def test_search_catalog_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 = DataCatalogClient( + 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.search_catalog), + '__call__') as call: + client.search_catalog() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + +@pytest.mark.asyncio +async def test_search_catalog_async(transport: str = 'grpc_asyncio', request_type=datacatalog.SearchCatalogRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.SearchCatalogRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_catalog_async_from_dict(): + await test_search_catalog_async(request_type=dict) + + +def test_search_catalog_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_catalog( + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) + assert args[0].query == 'query_value' + + +def test_search_catalog_flattened_error(): + client = DataCatalogClient( + 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.search_catalog( + datacatalog.SearchCatalogRequest(), + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_value', + ) + + +@pytest.mark.asyncio +async def test_search_catalog_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.SearchCatalogResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_catalog( + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) + assert args[0].query == 'query_value' + + +@pytest.mark.asyncio +async def test_search_catalog_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.search_catalog( + datacatalog.SearchCatalogRequest(), + scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), + query='query_value', + ) + + +def test_search_catalog_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.search_catalog(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, search.SearchCatalogResult) + for i in results) + +def test_search_catalog_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_catalog(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_search_catalog_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_catalog(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, search.SearchCatalogResult) + for i in responses) + +@pytest.mark.asyncio +async def test_search_catalog_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_catalog), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + next_page_token='abc', + ), + datacatalog.SearchCatalogResponse( + results=[], + next_page_token='def', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + ], + next_page_token='ghi', + ), + datacatalog.SearchCatalogResponse( + results=[ + search.SearchCatalogResult(), + search.SearchCatalogResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_catalog(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_entry_group(transport: str = 'grpc', request_type=datacatalog.CreateEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_entry_group_from_dict(): + test_create_entry_group(request_type=dict) + + +def test_create_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.create_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_create_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_entry_group_async_from_dict(): + await test_create_entry_group_async(request_type=dict) + + +def test_create_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.create_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.create_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entry_group( + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' + assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') + + +def test_create_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.CreateEntryGroupRequest(), + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entry_group( + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' + assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') + + +@pytest.mark.asyncio +async def test_create_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.CreateEntryGroupRequest(), + parent='parent_value', + entry_group_id='entry_group_id_value', + entry_group=datacatalog.EntryGroup(name='name_value'), + ) + + +def test_update_entry_group(transport: str = 'grpc', request_type=datacatalog.UpdateEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_entry_group_from_dict(): + test_update_entry_group(request_type=dict) + + +def test_update_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.update_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_update_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_entry_group_async_from_dict(): + await test_update_entry_group_async(request_type=dict) + + +def test_update_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryGroupRequest() + + request.entry_group.name = 'entry_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.update_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entry_group.name=entry_group.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryGroupRequest() + + request.entry_group.name = 'entry_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.update_entry_group(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', + 'entry_group.name=entry_group.name/value', + ) in kw['metadata'] + + +def test_update_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entry_group( + entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.UpdateEntryGroupRequest(), + entry_group=datacatalog.EntryGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entry_group( + entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.UpdateEntryGroupRequest(), + entry_group=datacatalog.EntryGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_entry_group(transport: str = 'grpc', request_type=datacatalog.GetEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_entry_group_from_dict(): + test_get_entry_group(request_type=dict) + + +def test_get_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.get_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_get_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.EntryGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_entry_group_async_from_dict(): + await test_get_entry_group_async(request_type=dict) + + +def test_get_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + call.return_value = datacatalog.EntryGroup() + client.get_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + await client.get_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entry_group( + name='name_value', + read_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].name == 'name_value' + assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_get_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.GetEntryGroupRequest(), + name='name_value', + read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_get_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.EntryGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entry_group( + name='name_value', + read_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].name == 'name_value' + assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_get_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.GetEntryGroupRequest(), + name='name_value', + read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_entry_group(transport: str = 'grpc', request_type=datacatalog.DeleteEntryGroupRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entry_group_from_dict(): + test_delete_entry_group(request_type=dict) + + +def test_delete_entry_group_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 = DataCatalogClient( + 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_entry_group), + '__call__') as call: + client.delete_entry_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + +@pytest.mark.asyncio +async def test_delete_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryGroupRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entry_group_async_from_dict(): + await test_delete_entry_group_async(request_type=dict) + + +def test_delete_entry_group_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__call__') as call: + call.return_value = None + client.delete_entry_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_group_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entry_group(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_entry_group_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__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_entry_group( + 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_entry_group_flattened_error(): + client = DataCatalogClient( + 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_entry_group( + datacatalog.DeleteEntryGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entry_group_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry_group), + '__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_entry_group( + 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_entry_group_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_group( + datacatalog.DeleteEntryGroupRequest(), + name='name_value', + ) + + +def test_list_entry_groups(transport: str = 'grpc', request_type=datacatalog.ListEntryGroupsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntryGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entry_groups_from_dict(): + test_list_entry_groups(request_type=dict) + + +def test_list_entry_groups_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 = DataCatalogClient( + 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_entry_groups), + '__call__') as call: + client.list_entry_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + +@pytest.mark.asyncio +async def test_list_entry_groups_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntryGroupsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntryGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntryGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entry_groups_async_from_dict(): + await test_list_entry_groups_async(request_type=dict) + + +def test_list_entry_groups_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntryGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + call.return_value = datacatalog.ListEntryGroupsResponse() + client.list_entry_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_groups_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntryGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) + await client.list_entry_groups(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_entry_groups_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entry_groups( + 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_entry_groups_flattened_error(): + client = DataCatalogClient( + 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_entry_groups( + datacatalog.ListEntryGroupsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_entry_groups_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntryGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entry_groups( + 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_entry_groups_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry_groups( + datacatalog.ListEntryGroupsRequest(), + parent='parent_value', + ) + + +def test_list_entry_groups_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entry_groups(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, datacatalog.EntryGroup) + for i in results) + +def test_list_entry_groups_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entry_groups(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_entry_groups_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entry_groups(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, datacatalog.EntryGroup) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entry_groups_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entry_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + next_page_token='abc', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[], + next_page_token='def', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntryGroupsResponse( + entry_groups=[ + datacatalog.EntryGroup(), + datacatalog.EntryGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entry_groups(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_entry(transport: str = 'grpc', request_type=datacatalog.CreateEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + ) + response = client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_entry_from_dict(): + test_create_entry(request_type=dict) + + +def test_create_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.create_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + +@pytest.mark.asyncio +async def test_create_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_entry_async_from_dict(): + await test_create_entry_async(request_type=dict) + + +def test_create_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.create_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateEntryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.create_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entry( + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(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].entry_id == 'entry_id_value' + assert args[0].entry == datacatalog.Entry(name='name_value') + + +def test_create_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.CreateEntryRequest(), + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entry( + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(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].entry_id == 'entry_id_value' + assert args[0].entry == datacatalog.Entry(name='name_value') + + +@pytest.mark.asyncio +async def test_create_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.CreateEntryRequest(), + parent='parent_value', + entry_id='entry_id_value', + entry=datacatalog.Entry(name='name_value'), + ) + + +def test_update_entry(transport: str = 'grpc', request_type=datacatalog.UpdateEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + ) + response = client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_entry_from_dict(): + test_update_entry(request_type=dict) + + +def test_update_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.update_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + +@pytest.mark.asyncio +async def test_update_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_entry_async_from_dict(): + await test_update_entry_async(request_type=dict) + + +def test_update_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryRequest() + + request.entry.name = 'entry.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.update_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entry.name=entry.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateEntryRequest() + + request.entry.name = 'entry.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.update_entry(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', + 'entry.name=entry.name/value', + ) in kw['metadata'] + + +def test_update_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entry( + entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.UpdateEntryRequest(), + entry=datacatalog.Entry(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entry( + entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.UpdateEntryRequest(), + entry=datacatalog.Entry(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_entry(transport: str = 'grpc', request_type=datacatalog.DeleteEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entry_from_dict(): + test_delete_entry(request_type=dict) + + +def test_delete_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.delete_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + +@pytest.mark.asyncio +async def test_delete_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteEntryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entry_async_from_dict(): + await test_delete_entry_async(request_type=dict) + + +def test_delete_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__call__') as call: + call.return_value = None + client.delete_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__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_entry( + 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_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.DeleteEntryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entry), + '__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_entry( + 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_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.DeleteEntryRequest(), + name='name_value', + ) + + +def test_get_entry(transport: str = 'grpc', request_type=datacatalog.GetEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + ) + response = client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_entry_from_dict(): + test_get_entry(request_type=dict) + + +def test_get_entry_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 = DataCatalogClient( + 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_entry), + '__call__') as call: + client.get_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + +@pytest.mark.asyncio +async def test_get_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_entry_async_from_dict(): + await test_get_entry_async(request_type=dict) + + +def test_get_entry_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + call.return_value = datacatalog.Entry() + client.get_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_entry_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetEntryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + await client.get_entry(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_entry_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entry( + 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_entry_flattened_error(): + client = DataCatalogClient( + 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_entry( + datacatalog.GetEntryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_entry_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entry( + 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_entry_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entry( + datacatalog.GetEntryRequest(), + name='name_value', + ) + + +def test_lookup_entry(transport: str = 'grpc', request_type=datacatalog.LookupEntryRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + type_=datacatalog.EntryType.TABLE, + integrated_system=common.IntegratedSystem.BIGQUERY, + gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), + ) + response = client.lookup_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_lookup_entry_from_dict(): + test_lookup_entry(request_type=dict) + + +def test_lookup_entry_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 = DataCatalogClient( + 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.lookup_entry), + '__call__') as call: + client.lookup_entry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + +@pytest.mark.asyncio +async def test_lookup_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.LookupEntryRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_entry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( + name='name_value', + linked_resource='linked_resource_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.lookup_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.LookupEntryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, datacatalog.Entry) + assert response.name == 'name_value' + assert response.linked_resource == 'linked_resource_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_lookup_entry_async_from_dict(): + await test_lookup_entry_async(request_type=dict) + + +def test_list_entries(transport: str = 'grpc', request_type=datacatalog.ListEntriesRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entries_from_dict(): + test_list_entries(request_type=dict) + + +def test_list_entries_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 = DataCatalogClient( + 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_entries), + '__call__') as call: + client.list_entries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + +@pytest.mark.asyncio +async def test_list_entries_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntriesRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListEntriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entries_async_from_dict(): + await test_list_entries_async(request_type=dict) + + +def test_list_entries_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + call.return_value = datacatalog.ListEntriesResponse() + client.list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entries_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListEntriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) + await client.list_entries(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_entries_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entries( + 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_entries_flattened_error(): + client = DataCatalogClient( + 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_entries( + datacatalog.ListEntriesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_entries_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListEntriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entries( + 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_entries_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_entries( + datacatalog.ListEntriesRequest(), + parent='parent_value', + ) + + +def test_list_entries_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entries(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, datacatalog.Entry) + for i in results) + +def test_list_entries_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entries(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_entries_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entries(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, datacatalog.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entries_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + datacatalog.Entry(), + ], + next_page_token='abc', + ), + datacatalog.ListEntriesResponse( + entries=[], + next_page_token='def', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + ], + next_page_token='ghi', + ), + datacatalog.ListEntriesResponse( + entries=[ + datacatalog.Entry(), + datacatalog.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entries(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_tag_template(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + ) + response = client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_tag_template_from_dict(): + test_create_tag_template(request_type=dict) + + +def test_create_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.create_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_create_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_tag_template_async_from_dict(): + await test_create_tag_template_async(request_type=dict) + + +def test_create_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.create_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.create_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag_template( + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' + assert args[0].tag_template == tags.TagTemplate(name='name_value') + + +def test_create_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.CreateTagTemplateRequest(), + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag_template( + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' + assert args[0].tag_template == tags.TagTemplate(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.CreateTagTemplateRequest(), + parent='parent_value', + tag_template_id='tag_template_id_value', + tag_template=tags.TagTemplate(name='name_value'), + ) + + +def test_get_tag_template(transport: str = 'grpc', request_type=datacatalog.GetTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + ) + response = client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_tag_template_from_dict(): + test_get_tag_template(request_type=dict) + + +def test_get_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.get_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_get_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.GetTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_tag_template_async_from_dict(): + await test_get_tag_template_async(request_type=dict) + + +def test_get_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.get_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.GetTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.get_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tag_template( + 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_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.GetTagTemplateRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tag_template( + 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_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.GetTagTemplateRequest(), + name='name_value', + ) + + +def test_update_tag_template(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate( + name='name_value', + display_name='display_name_value', + ) + response = client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_tag_template_from_dict(): + test_update_tag_template(request_type=dict) + + +def test_update_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.update_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_update_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplate) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_tag_template_async_from_dict(): + await test_update_tag_template_async(request_type=dict) + + +def test_update_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateRequest() + + request.tag_template.name = 'tag_template.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + call.return_value = tags.TagTemplate() + client.update_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag_template.name=tag_template.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateRequest() + + request.tag_template.name = 'tag_template.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + await client.update_tag_template(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', + 'tag_template.name=tag_template.name/value', + ) in kw['metadata'] + + +def test_update_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_template( + tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.UpdateTagTemplateRequest(), + tag_template=tags.TagTemplate(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplate() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_template( + tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.UpdateTagTemplateRequest(), + tag_template=tags.TagTemplate(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_tag_template(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_template_from_dict(): + test_delete_tag_template(request_type=dict) + + +def test_delete_tag_template_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 = DataCatalogClient( + 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_tag_template), + '__call__') as call: + client.delete_tag_template() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_template_async_from_dict(): + await test_delete_tag_template_async(request_type=dict) + + +def test_delete_tag_template_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__call__') as call: + call.return_value = None + client.delete_tag_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag_template(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_tag_template_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__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_tag_template( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +def test_delete_tag_template_flattened_error(): + client = DataCatalogClient( + 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_tag_template( + datacatalog.DeleteTagTemplateRequest(), + name='name_value', + force=True, + ) + + +@pytest.mark.asyncio +async def test_delete_tag_template_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template), + '__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_tag_template( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +@pytest.mark.asyncio +async def test_delete_tag_template_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template( + datacatalog.DeleteTagTemplateRequest(), + name='name_value', + force=True, + ) + + +def test_create_tag_template_field(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + ) + response = client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +def test_create_tag_template_field_from_dict(): + test_create_tag_template_field(request_type=dict) + + +def test_create_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.create_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_create_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + )) + response = await client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_create_tag_template_field_async_from_dict(): + await test_create_tag_template_field_async(request_type=dict) + + +def test_create_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateFieldRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.create_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagTemplateFieldRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.create_tag_template_field(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_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag_template_field( + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + + +def test_create_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.CreateTagTemplateFieldRequest(), + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag_template_field( + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.CreateTagTemplateFieldRequest(), + parent='parent_value', + tag_template_field_id='tag_template_field_id_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + ) + + +def test_update_tag_template_field(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + ) + response = client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +def test_update_tag_template_field_from_dict(): + test_update_tag_template_field(request_type=dict) + + +def test_update_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.update_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_update_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + )) + response = await client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_update_tag_template_field_async_from_dict(): + await test_update_tag_template_field_async(request_type=dict) + + +def test_update_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.update_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_update_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.update_tag_template_field(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_update_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_template_field( + name='name_value', + tag_template_field=tags.TagTemplateField(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].name == 'name_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.UpdateTagTemplateFieldRequest(), + name='name_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_template_field( + name='name_value', + tag_template_field=tags.TagTemplateField(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].name == 'name_value' + assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.UpdateTagTemplateFieldRequest(), + name='name_value', + tag_template_field=tags.TagTemplateField(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_rename_tag_template_field(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + ) + response = client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +def test_rename_tag_template_field_from_dict(): + test_rename_tag_template_field(request_type=dict) + + +def test_rename_tag_template_field_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 = DataCatalogClient( + 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.rename_tag_template_field), + '__call__') as call: + client.rename_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( + name='name_value', + display_name='display_name_value', + is_required=True, + order=540, + )) + response = await client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.RenameTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.TagTemplateField) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.is_required is True + assert response.order == 540 + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_async_from_dict(): + await test_rename_tag_template_field_async(request_type=dict) + + +def test_rename_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + call.return_value = tags.TagTemplateField() + client.rename_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_rename_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.RenameTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + await client.rename_tag_template_field(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_rename_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.rename_tag_template_field( + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' + + +def test_rename_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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.rename_tag_template_field( + datacatalog.RenameTagTemplateFieldRequest(), + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rename_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.TagTemplateField() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.rename_tag_template_field( + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' + + +@pytest.mark.asyncio +async def test_rename_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.rename_tag_template_field( + datacatalog.RenameTagTemplateFieldRequest(), + name='name_value', + new_tag_template_field_id='new_tag_template_field_id_value', + ) + + +def test_delete_tag_template_field(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateFieldRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_template_field_from_dict(): + test_delete_tag_template_field(request_type=dict) + + +def test_delete_tag_template_field_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 = DataCatalogClient( + 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_tag_template_field), + '__call__') as call: + client.delete_tag_template_field() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateFieldRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_template_field), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_async_from_dict(): + await test_delete_tag_template_field_async(request_type=dict) + + +def test_delete_tag_template_field_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__call__') as call: + call.return_value = None + client.delete_tag_template_field(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_template_field_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagTemplateFieldRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag_template_field(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_tag_template_field_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__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_tag_template_field( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +def test_delete_tag_template_field_flattened_error(): + client = DataCatalogClient( + 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_tag_template_field( + datacatalog.DeleteTagTemplateFieldRequest(), + name='name_value', + force=True, + ) + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_template_field), + '__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_tag_template_field( + name='name_value', + force=True, + ) + + # 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' + assert args[0].force == True + + +@pytest.mark.asyncio +async def test_delete_tag_template_field_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag_template_field( + datacatalog.DeleteTagTemplateFieldRequest(), + name='name_value', + force=True, + ) + + +def test_create_tag(transport: str = 'grpc', request_type=datacatalog.CreateTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + column='column_value', + ) + response = client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +def test_create_tag_from_dict(): + test_create_tag(request_type=dict) + + +def test_create_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.create_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + +@pytest.mark.asyncio +async def test_create_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + )) + response = await client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.CreateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +@pytest.mark.asyncio +async def test_create_tag_async_from_dict(): + await test_create_tag_async(request_type=dict) + + +def test_create_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + call.return_value = tags.Tag() + client.create_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.CreateTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + await client.create_tag(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_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tag( + parent='parent_value', + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + + +def test_create_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.CreateTagRequest(), + parent='parent_value', + tag=tags.Tag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tag( + parent='parent_value', + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + + +@pytest.mark.asyncio +async def test_create_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.CreateTagRequest(), + parent='parent_value', + tag=tags.Tag(name='name_value'), + ) + + +def test_update_tag(transport: str = 'grpc', request_type=datacatalog.UpdateTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + column='column_value', + ) + response = client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +def test_update_tag_from_dict(): + test_update_tag(request_type=dict) + + +def test_update_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.update_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + +@pytest.mark.asyncio +async def test_update_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( + name='name_value', + template='template_value', + template_display_name='template_display_name_value', + )) + response = await client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.UpdateTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tags.Tag) + assert response.name == 'name_value' + assert response.template == 'template_value' + assert response.template_display_name == 'template_display_name_value' + + +@pytest.mark.asyncio +async def test_update_tag_async_from_dict(): + await test_update_tag_async(request_type=dict) + + +def test_update_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagRequest() + + request.tag.name = 'tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + call.return_value = tags.Tag() + client.update_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag.name=tag.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.UpdateTagRequest() + + request.tag.name = 'tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + await client.update_tag(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', + 'tag.name=tag.name/value', + ) in kw['metadata'] + + +def test_update_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag( + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.UpdateTagRequest(), + tag=tags.Tag(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tags.Tag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag( + tag=tags.Tag(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].tag == tags.Tag(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.UpdateTagRequest(), + tag=tags.Tag(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_tag(transport: str = 'grpc', request_type=datacatalog.DeleteTagRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tag_from_dict(): + test_delete_tag(request_type=dict) + + +def test_delete_tag_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 = DataCatalogClient( + 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_tag), + '__call__') as call: + client.delete_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + +@pytest.mark.asyncio +async def test_delete_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.DeleteTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tag_async_from_dict(): + await test_delete_tag_async(request_type=dict) + + +def test_delete_tag_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__call__') as call: + call.return_value = None + client.delete_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_tag_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.DeleteTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tag(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_tag_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__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_tag( + 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_tag_flattened_error(): + client = DataCatalogClient( + 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_tag( + datacatalog.DeleteTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_tag_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag), + '__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_tag( + 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_tag_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tag( + datacatalog.DeleteTagRequest(), + name='name_value', + ) + + +def test_list_tags(transport: str = 'grpc', request_type=datacatalog.ListTagsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tags_from_dict(): + test_list_tags(request_type=dict) + + +def test_list_tags_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 = DataCatalogClient( + 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_tags), + '__call__') as call: + client.list_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + +@pytest.mark.asyncio +async def test_list_tags_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListTagsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == datacatalog.ListTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tags_async_from_dict(): + await test_list_tags_async(request_type=dict) + + +def test_list_tags_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + call.return_value = datacatalog.ListTagsResponse() + client.list_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_tags_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datacatalog.ListTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) + await client.list_tags(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_tags_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tags( + 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_tags_flattened_error(): + client = DataCatalogClient( + 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_tags( + datacatalog.ListTagsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_tags_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = datacatalog.ListTagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tags( + 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_tags_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_tags( + datacatalog.ListTagsRequest(), + parent='parent_value', + ) + + +def test_list_tags_pager(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_tags(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, tags.Tag) + for i in results) + +def test_list_tags_pages(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tags(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_tags_async_pager(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tags(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, tags.Tag) + for i in responses) + +@pytest.mark.asyncio +async def test_list_tags_async_pages(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + tags.Tag(), + ], + next_page_token='abc', + ), + datacatalog.ListTagsResponse( + tags=[], + next_page_token='def', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + ], + next_page_token='ghi', + ), + datacatalog.ListTagsResponse( + tags=[ + tags.Tag(), + tags.Tag(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_tags(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataCatalogClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_set_iam_policy_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy(request={ + 'resource': 'resource_value', + 'policy': policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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].resource == 'resource_value' + + +def test_set_iam_policy_flattened_error(): + client = DataCatalogClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_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].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = DataCatalogAsyncClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataCatalogClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_get_iam_policy_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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].resource == 'resource_value' + + +def test_get_iam_policy_flattened_error(): + client = DataCatalogClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_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].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = DataCatalogAsyncClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = DataCatalogClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + )) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_test_iam_permissions_from_dict_foreign(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions(request={ + 'resource': 'resource_value', + 'permissions': ['permissions_value'], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataCatalogClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataCatalogClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataCatalogGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataCatalogGrpcTransport, + transports.DataCatalogGrpcAsyncIOTransport, +]) +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 = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataCatalogGrpcTransport, + ) + +def test_data_catalog_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataCatalogTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_catalog_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataCatalogTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search_catalog', + 'create_entry_group', + 'update_entry_group', + 'get_entry_group', + 'delete_entry_group', + 'list_entry_groups', + 'create_entry', + 'update_entry', + 'delete_entry', + 'get_entry', + 'lookup_entry', + 'list_entries', + 'create_tag_template', + 'get_tag_template', + 'update_tag_template', + 'delete_tag_template', + 'create_tag_template_field', + 'update_tag_template_field', + 'rename_tag_template_field', + 'delete_tag_template_field', + 'create_tag', + 'update_tag', + 'delete_tag', + 'list_tags', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_data_catalog_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.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataCatalogTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_data_catalog_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.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataCatalogTransport() + adc.assert_called_once() + + +def test_data_catalog_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) + DataCatalogClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataCatalogGrpcTransport, + transports.DataCatalogGrpcAsyncIOTransport, + ], +) +def test_data_catalog_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,grpc_helpers", + [ + (transports.DataCatalogGrpcTransport, grpc_helpers), + (transports.DataCatalogGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_catalog_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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_catalog_host_no_port(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_data_catalog_host_with_port(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_data_catalog_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataCatalogGrpcTransport( + 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_catalog_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataCatalogGrpcAsyncIOTransport( + 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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) +def test_data_catalog_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_entry_path(): + project = "squid" + location = "clam" + entry_group = "whelk" + entry = "octopus" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) + actual = DataCatalogClient.entry_path(project, location, entry_group, entry) + assert expected == actual + + +def test_parse_entry_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "entry_group": "cuttlefish", + "entry": "mussel", + } + path = DataCatalogClient.entry_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_entry_path(path) + assert expected == actual + +def test_entry_group_path(): + project = "winkle" + location = "nautilus" + entry_group = "scallop" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) + actual = DataCatalogClient.entry_group_path(project, location, entry_group) + assert expected == actual + + +def test_parse_entry_group_path(): + expected = { + "project": "abalone", + "location": "squid", + "entry_group": "clam", + } + path = DataCatalogClient.entry_group_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_entry_group_path(path) + assert expected == actual + +def test_tag_path(): + project = "whelk" + location = "octopus" + entry_group = "oyster" + entry = "nudibranch" + tag = "cuttlefish" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) + actual = DataCatalogClient.tag_path(project, location, entry_group, entry, tag) + assert expected == actual + + +def test_parse_tag_path(): + expected = { + "project": "mussel", + "location": "winkle", + "entry_group": "nautilus", + "entry": "scallop", + "tag": "abalone", + } + path = DataCatalogClient.tag_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_path(path) + assert expected == actual + +def test_tag_template_path(): + project = "squid" + location = "clam" + tag_template = "whelk" + expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) + actual = DataCatalogClient.tag_template_path(project, location, tag_template) + assert expected == actual + + +def test_parse_tag_template_path(): + expected = { + "project": "octopus", + "location": "oyster", + "tag_template": "nudibranch", + } + path = DataCatalogClient.tag_template_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_template_path(path) + assert expected == actual + +def test_tag_template_field_path(): + project = "cuttlefish" + location = "mussel" + tag_template = "winkle" + field = "nautilus" + expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) + actual = DataCatalogClient.tag_template_field_path(project, location, tag_template, field) + assert expected == actual + + +def test_parse_tag_template_field_path(): + expected = { + "project": "scallop", + "location": "abalone", + "tag_template": "squid", + "field": "clam", + } + path = DataCatalogClient.tag_template_field_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_tag_template_field_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataCatalogClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DataCatalogClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataCatalogClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DataCatalogClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataCatalogClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DataCatalogClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DataCatalogClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DataCatalogClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.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 = DataCatalogClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DataCatalogClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataCatalogClient.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.DataCatalogTransport, '_prep_wrapped_messages') as prep: + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataCatalogTransport, '_prep_wrapped_messages') as prep: + transport_class = DataCatalogClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DataCatalogAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = DataCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py new file mode 100644 index 00000000..464a5814 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py @@ -0,0 +1,4233 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import PolicyTagManagerAsyncClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import PolicyTagManagerClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import transports +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PolicyTagManagerClient._get_default_mtls_endpoint(None) is None + assert PolicyTagManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PolicyTagManagerClient, + PolicyTagManagerAsyncClient, +]) +def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PolicyTagManagerGrpcTransport, "grpc"), + (transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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", [ + PolicyTagManagerClient, + PolicyTagManagerAsyncClient, +]) +def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_client_get_transport_class(): + transport = PolicyTagManagerClient.get_transport_class() + available_transports = [ + transports.PolicyTagManagerGrpcTransport, + ] + assert transport in available_transports + + transport = PolicyTagManagerClient.get_transport_class("grpc") + assert transport == transports.PolicyTagManagerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) +@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) +def test_policy_tag_manager_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(PolicyTagManagerClient, '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(PolicyTagManagerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "true"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "false"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) +@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_policy_tag_manager_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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(transport=transport_name, 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", [ + (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), + (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_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(transport=transport_name, 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_policy_tag_manager_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PolicyTagManagerClient( + 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_create_taxonomy(transport: str = 'grpc', request_type=policytagmanager.CreateTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_create_taxonomy_from_dict(): + test_create_taxonomy(request_type=dict) + + +def test_create_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.create_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_create_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreateTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_create_taxonomy_async_from_dict(): + await test_create_taxonomy_async(request_type=dict) + + +def test_create_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreateTaxonomyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.create_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreateTaxonomyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.create_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_taxonomy( + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +def test_create_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.CreateTaxonomyRequest(), + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_taxonomy( + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +@pytest.mark.asyncio +async def test_create_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.CreateTaxonomyRequest(), + parent='parent_value', + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +def test_delete_taxonomy(transport: str = 'grpc', request_type=policytagmanager.DeleteTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_taxonomy_from_dict(): + test_delete_taxonomy(request_type=dict) + + +def test_delete_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.delete_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_delete_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeleteTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeleteTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_taxonomy_async_from_dict(): + await test_delete_taxonomy_async(request_type=dict) + + +def test_delete_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeleteTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__call__') as call: + call.return_value = None + client.delete_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeleteTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__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_taxonomy( + 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_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.DeleteTaxonomyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_taxonomy), + '__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_taxonomy( + 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_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.DeleteTaxonomyRequest(), + name='name_value', + ) + + +def test_update_taxonomy(transport: str = 'grpc', request_type=policytagmanager.UpdateTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_update_taxonomy_from_dict(): + test_update_taxonomy(request_type=dict) + + +def test_update_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.update_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_update_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdateTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdateTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_update_taxonomy_async_from_dict(): + await test_update_taxonomy_async(request_type=dict) + + +def test_update_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdateTaxonomyRequest() + + request.taxonomy.name = 'taxonomy.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.update_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'taxonomy.name=taxonomy.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdateTaxonomyRequest() + + request.taxonomy.name = 'taxonomy.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.update_taxonomy(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', + 'taxonomy.name=taxonomy.name/value', + ) in kw['metadata'] + + +def test_update_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_taxonomy( + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +def test_update_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.UpdateTaxonomyRequest(), + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_taxonomy( + taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') + + +@pytest.mark.asyncio +async def test_update_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.UpdateTaxonomyRequest(), + taxonomy=policytagmanager.Taxonomy(name='name_value'), + ) + + +def test_list_taxonomies(transport: str = 'grpc', request_type=policytagmanager.ListTaxonomiesRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTaxonomiesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_taxonomies_from_dict(): + test_list_taxonomies(request_type=dict) + + +def test_list_taxonomies_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 = PolicyTagManagerClient( + 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_taxonomies), + '__call__') as call: + client.list_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_list_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListTaxonomiesRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTaxonomiesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_taxonomies_async_from_dict(): + await test_list_taxonomies_async(request_type=dict) + + +def test_list_taxonomies_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + call.return_value = policytagmanager.ListTaxonomiesResponse() + client.list_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_taxonomies_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) + await client.list_taxonomies(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_taxonomies_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_taxonomies( + 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_taxonomies_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomies( + policytagmanager.ListTaxonomiesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_taxonomies_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListTaxonomiesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_taxonomies( + 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_taxonomies_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomies( + policytagmanager.ListTaxonomiesRequest(), + parent='parent_value', + ) + + +def test_list_taxonomies_pager(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_taxonomies(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, policytagmanager.Taxonomy) + for i in results) + +def test_list_taxonomies_pages(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_taxonomies(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_taxonomies_async_pager(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_taxonomies(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, policytagmanager.Taxonomy) + for i in responses) + +@pytest.mark.asyncio +async def test_list_taxonomies_async_pages(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_taxonomies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + next_page_token='abc', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[], + next_page_token='def', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + ], + next_page_token='ghi', + ), + policytagmanager.ListTaxonomiesResponse( + taxonomies=[ + policytagmanager.Taxonomy(), + policytagmanager.Taxonomy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_taxonomies(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_taxonomy(transport: str = 'grpc', request_type=policytagmanager.GetTaxonomyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + ) + response = client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +def test_get_taxonomy_from_dict(): + test_get_taxonomy(request_type=dict) + + +def test_get_taxonomy_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 = PolicyTagManagerClient( + 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_taxonomy), + '__call__') as call: + client.get_taxonomy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + +@pytest.mark.asyncio +async def test_get_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetTaxonomyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( + name='name_value', + display_name='display_name_value', + description='description_value', + activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], + )) + response = await client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetTaxonomyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.Taxonomy) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] + + +@pytest.mark.asyncio +async def test_get_taxonomy_async_from_dict(): + await test_get_taxonomy_async(request_type=dict) + + +def test_get_taxonomy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + call.return_value = policytagmanager.Taxonomy() + client.get_taxonomy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_taxonomy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetTaxonomyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + await client.get_taxonomy(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_taxonomy_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_taxonomy( + 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_taxonomy_flattened_error(): + client = PolicyTagManagerClient( + 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_taxonomy( + policytagmanager.GetTaxonomyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_taxonomy_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_taxonomy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.Taxonomy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_taxonomy( + 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_taxonomy_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_taxonomy( + policytagmanager.GetTaxonomyRequest(), + name='name_value', + ) + + +def test_create_policy_tag(transport: str = 'grpc', request_type=policytagmanager.CreatePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_create_policy_tag_from_dict(): + test_create_policy_tag(request_type=dict) + + +def test_create_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.create_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_create_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreatePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.CreatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_create_policy_tag_async_from_dict(): + await test_create_policy_tag_async(request_type=dict) + + +def test_create_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreatePolicyTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.create_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.CreatePolicyTagRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.create_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_policy_tag( + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +def test_create_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.CreatePolicyTagRequest(), + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_policy_tag( + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +@pytest.mark.asyncio +async def test_create_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.CreatePolicyTagRequest(), + parent='parent_value', + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +def test_delete_policy_tag(transport: str = 'grpc', request_type=policytagmanager.DeletePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_policy_tag_from_dict(): + test_delete_policy_tag(request_type=dict) + + +def test_delete_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.delete_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_delete_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeletePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.DeletePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_policy_tag_async_from_dict(): + await test_delete_policy_tag_async(request_type=dict) + + +def test_delete_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeletePolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__call__') as call: + call.return_value = None + client.delete_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.DeletePolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__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_policy_tag( + 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_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.DeletePolicyTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_tag), + '__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_policy_tag( + 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_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.DeletePolicyTagRequest(), + name='name_value', + ) + + +def test_update_policy_tag(transport: str = 'grpc', request_type=policytagmanager.UpdatePolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_update_policy_tag_from_dict(): + test_update_policy_tag(request_type=dict) + + +def test_update_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.update_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + +@pytest.mark.asyncio +async def test_update_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdatePolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.UpdatePolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_update_policy_tag_async_from_dict(): + await test_update_policy_tag_async(request_type=dict) + + +def test_update_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdatePolicyTagRequest() + + request.policy_tag.name = 'policy_tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.update_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'policy_tag.name=policy_tag.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.UpdatePolicyTagRequest() + + request.policy_tag.name = 'policy_tag.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.update_policy_tag(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', + 'policy_tag.name=policy_tag.name/value', + ) in kw['metadata'] + + +def test_update_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_policy_tag( + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +def test_update_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.UpdatePolicyTagRequest(), + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_policy_tag( + policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') + + +@pytest.mark.asyncio +async def test_update_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.UpdatePolicyTagRequest(), + policy_tag=policytagmanager.PolicyTag(name='name_value'), + ) + + +def test_list_policy_tags(transport: str = 'grpc', request_type=policytagmanager.ListPolicyTagsRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyTagsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_policy_tags_from_dict(): + test_list_policy_tags(request_type=dict) + + +def test_list_policy_tags_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 = PolicyTagManagerClient( + 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_policy_tags), + '__call__') as call: + client.list_policy_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + +@pytest.mark.asyncio +async def test_list_policy_tags_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListPolicyTagsRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.ListPolicyTagsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyTagsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_policy_tags_async_from_dict(): + await test_list_policy_tags_async(request_type=dict) + + +def test_list_policy_tags_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListPolicyTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + call.return_value = policytagmanager.ListPolicyTagsResponse() + client.list_policy_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_policy_tags_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.ListPolicyTagsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) + await client.list_policy_tags(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_policy_tags_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_policy_tags( + 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_policy_tags_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tags( + policytagmanager.ListPolicyTagsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_policy_tags_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.ListPolicyTagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_policy_tags( + 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_policy_tags_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tags( + policytagmanager.ListPolicyTagsRequest(), + parent='parent_value', + ) + + +def test_list_policy_tags_pager(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_policy_tags(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, policytagmanager.PolicyTag) + for i in results) + +def test_list_policy_tags_pages(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + pages = list(client.list_policy_tags(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_policy_tags_async_pager(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_policy_tags(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, policytagmanager.PolicyTag) + for i in responses) + +@pytest.mark.asyncio +async def test_list_policy_tags_async_pages(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_tags), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + next_page_token='abc', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[], + next_page_token='def', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + ], + next_page_token='ghi', + ), + policytagmanager.ListPolicyTagsResponse( + policy_tags=[ + policytagmanager.PolicyTag(), + policytagmanager.PolicyTag(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_policy_tags(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_policy_tag(transport: str = 'grpc', request_type=policytagmanager.GetPolicyTagRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + ) + response = client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +def test_get_policy_tag_from_dict(): + test_get_policy_tag(request_type=dict) + + +def test_get_policy_tag_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 = PolicyTagManagerClient( + 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_policy_tag), + '__call__') as call: + client.get_policy_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + +@pytest.mark.asyncio +async def test_get_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetPolicyTagRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( + name='name_value', + display_name='display_name_value', + description='description_value', + parent_policy_tag='parent_policy_tag_value', + child_policy_tags=['child_policy_tags_value'], + )) + response = await client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanager.GetPolicyTagRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanager.PolicyTag) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.parent_policy_tag == 'parent_policy_tag_value' + assert response.child_policy_tags == ['child_policy_tags_value'] + + +@pytest.mark.asyncio +async def test_get_policy_tag_async_from_dict(): + await test_get_policy_tag_async(request_type=dict) + + +def test_get_policy_tag_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetPolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + call.return_value = policytagmanager.PolicyTag() + client.get_policy_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_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_policy_tag_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanager.GetPolicyTagRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + await client.get_policy_tag(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_policy_tag_flattened(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_policy_tag( + 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_policy_tag_flattened_error(): + client = PolicyTagManagerClient( + 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_policy_tag( + policytagmanager.GetPolicyTagRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_policy_tag_flattened_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanager.PolicyTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_policy_tag( + 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_policy_tag_flattened_error_async(): + client = PolicyTagManagerAsyncClient( + 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_policy_tag( + policytagmanager.GetPolicyTagRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PolicyTagManagerClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_get_iam_policy_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PolicyTagManagerClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_set_iam_policy_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy(request={ + 'resource': 'resource_value', + 'policy': policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = PolicyTagManagerClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + )) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'resource=resource/value', + ) in kw['metadata'] + +def test_test_iam_permissions_from_dict_foreign(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions(request={ + 'resource': 'resource_value', + 'permissions': ['permissions_value'], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PolicyTagManagerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PolicyTagManagerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PolicyTagManagerGrpcTransport, + transports.PolicyTagManagerGrpcAsyncIOTransport, +]) +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 = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PolicyTagManagerGrpcTransport, + ) + +def test_policy_tag_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PolicyTagManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_policy_tag_manager_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PolicyTagManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_taxonomy', + 'delete_taxonomy', + 'update_taxonomy', + 'list_taxonomies', + 'get_taxonomy', + 'create_policy_tag', + 'delete_policy_tag', + 'update_policy_tag', + 'list_policy_tags', + 'get_policy_tag', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_policy_tag_manager_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.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_policy_tag_manager_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.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerTransport() + adc.assert_called_once() + + +def test_policy_tag_manager_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) + PolicyTagManagerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyTagManagerGrpcTransport, + transports.PolicyTagManagerGrpcAsyncIOTransport, + ], +) +def test_policy_tag_manager_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,grpc_helpers", + [ + (transports.PolicyTagManagerGrpcTransport, grpc_helpers), + (transports.PolicyTagManagerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_policy_tag_manager_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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_policy_tag_manager_host_no_port(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_host_with_port(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_policy_tag_manager_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerGrpcTransport( + 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_policy_tag_manager_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerGrpcAsyncIOTransport( + 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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) +def test_policy_tag_manager_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_policy_tag_path(): + project = "squid" + location = "clam" + taxonomy = "whelk" + policy_tag = "octopus" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) + actual = PolicyTagManagerClient.policy_tag_path(project, location, taxonomy, policy_tag) + assert expected == actual + + +def test_parse_policy_tag_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "taxonomy": "cuttlefish", + "policy_tag": "mussel", + } + path = PolicyTagManagerClient.policy_tag_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_policy_tag_path(path) + assert expected == actual + +def test_taxonomy_path(): + project = "winkle" + location = "nautilus" + taxonomy = "scallop" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + actual = PolicyTagManagerClient.taxonomy_path(project, location, taxonomy) + assert expected == actual + + +def test_parse_taxonomy_path(): + expected = { + "project": "abalone", + "location": "squid", + "taxonomy": "clam", + } + path = PolicyTagManagerClient.taxonomy_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_taxonomy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PolicyTagManagerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = PolicyTagManagerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = PolicyTagManagerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = PolicyTagManagerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PolicyTagManagerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = PolicyTagManagerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = PolicyTagManagerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = PolicyTagManagerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.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 = PolicyTagManagerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = PolicyTagManagerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerClient.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.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: + transport_class = PolicyTagManagerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = PolicyTagManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = PolicyTagManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py new file mode 100644 index 00000000..0901a0b6 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py @@ -0,0 +1,1210 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient +from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import transports +from google.cloud.datacatalog_v1beta1.types import policytagmanager +from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(None) is None + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PolicyTagManagerSerializationClient, + PolicyTagManagerSerializationAsyncClient, +]) +def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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", [ + PolicyTagManagerSerializationClient, + PolicyTagManagerSerializationAsyncClient, +]) +def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_serialization_client_get_transport_class(): + transport = PolicyTagManagerSerializationClient.get_transport_class() + available_transports = [ + transports.PolicyTagManagerSerializationGrpcTransport, + ] + assert transport in available_transports + + transport = PolicyTagManagerSerializationClient.get_transport_class("grpc") + assert transport == transports.PolicyTagManagerSerializationGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) +@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) +def test_policy_tag_manager_serialization_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(PolicyTagManagerSerializationClient, '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(PolicyTagManagerSerializationClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, 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", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "true"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "false"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) +@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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", [ + (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), + (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_policy_tag_manager_serialization_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(transport=transport_name, 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_policy_tag_manager_serialization_client_client_options_from_dict(): + with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PolicyTagManagerSerializationClient( + 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_import_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse( + ) + response = client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) + + +def test_import_taxonomies_from_dict(): + test_import_taxonomies(request_type=dict) + + +def test_import_taxonomies_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 = PolicyTagManagerSerializationClient( + 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.import_taxonomies), + '__call__') as call: + client.import_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_import_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse( + )) + response = await client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) + + +@pytest.mark.asyncio +async def test_import_taxonomies_async_from_dict(): + await test_import_taxonomies_async(request_type=dict) + + +def test_import_taxonomies_field_headers(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ImportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse() + client.import_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_import_taxonomies_field_headers_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ImportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse()) + await client.import_taxonomies(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_export_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse( + ) + response = client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) + + +def test_export_taxonomies_from_dict(): + test_export_taxonomies(request_type=dict) + + +def test_export_taxonomies_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 = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + client.export_taxonomies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + +@pytest.mark.asyncio +async def test_export_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse( + )) + response = await client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) + + +@pytest.mark.asyncio +async def test_export_taxonomies_async_from_dict(): + await test_export_taxonomies_async(request_type=dict) + + +def test_export_taxonomies_field_headers(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ExportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse() + client.export_taxonomies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_export_taxonomies_field_headers_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = policytagmanagerserialization.ExportTaxonomiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_taxonomies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse()) + await client.export_taxonomies(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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyTagManagerSerializationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PolicyTagManagerSerializationClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PolicyTagManagerSerializationGrpcTransport, + transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, +]) +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 = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PolicyTagManagerSerializationGrpcTransport, + ) + +def test_policy_tag_manager_serialization_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PolicyTagManagerSerializationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_policy_tag_manager_serialization_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PolicyTagManagerSerializationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'import_taxonomies', + 'export_taxonomies', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_policy_tag_manager_serialization_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.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerSerializationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_policy_tag_manager_serialization_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.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyTagManagerSerializationTransport() + adc.assert_called_once() + + +def test_policy_tag_manager_serialization_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) + PolicyTagManagerSerializationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyTagManagerSerializationGrpcTransport, + transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, + ], +) +def test_policy_tag_manager_serialization_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,grpc_helpers", + [ + (transports.PolicyTagManagerSerializationGrpcTransport, grpc_helpers), + (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_policy_tag_manager_serialization_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( + "datacatalog.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="datacatalog.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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_policy_tag_manager_serialization_host_no_port(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:443' + + +def test_policy_tag_manager_serialization_host_with_port(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), + ) + assert client.transport._host == 'datacatalog.googleapis.com:8000' + +def test_policy_tag_manager_serialization_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerSerializationGrpcTransport( + 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_policy_tag_manager_serialization_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( + 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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) +def test_policy_tag_manager_serialization_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_taxonomy_path(): + project = "squid" + location = "clam" + taxonomy = "whelk" + expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) + actual = PolicyTagManagerSerializationClient.taxonomy_path(project, location, taxonomy) + assert expected == actual + + +def test_parse_taxonomy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "taxonomy": "nudibranch", + } + path = PolicyTagManagerSerializationClient.taxonomy_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_taxonomy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PolicyTagManagerSerializationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = PolicyTagManagerSerializationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = PolicyTagManagerSerializationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = PolicyTagManagerSerializationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PolicyTagManagerSerializationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = PolicyTagManagerSerializationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = PolicyTagManagerSerializationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = PolicyTagManagerSerializationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = PolicyTagManagerSerializationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = PolicyTagManagerSerializationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyTagManagerSerializationClient.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.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: + transport_class = PolicyTagManagerSerializationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = PolicyTagManagerSerializationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = PolicyTagManagerSerializationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() From 47e21be2812206a70ea7409e7b37b59972f26dc5 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 8 Nov 2021 10:50:49 +0000 Subject: [PATCH 2/3] =?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 --- .../services/data_catalog/async_client.py | 18 +- .../services/data_catalog/client.py | 18 +- .../services/data_catalog/transports/grpc.py | 4 + .../data_catalog/transports/grpc_asyncio.py | 4 + .../policy_tag_manager/async_client.py | 2 +- .../services/policy_tag_manager/client.py | 2 +- google/cloud/datacatalog_v1/types/bigquery.py | 1 - .../cloud/datacatalog_v1/types/datacatalog.py | 26 +- .../datacatalog_v1/types/policytagmanager.py | 4 +- .../types/policytagmanagerserialization.py | 3 - google/cloud/datacatalog_v1/types/search.py | 10 +- .../cloud/datacatalog_v1/types/table_spec.py | 6 +- google/cloud/datacatalog_v1/types/tags.py | 9 - .../datacatalog_v1beta1/types/datacatalog.py | 9 - .../types/policytagmanagerserialization.py | 1 - .../datacatalog_v1beta1/types/table_spec.py | 2 - .../cloud/datacatalog_v1beta1/types/tags.py | 8 - owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 - .../v1/docs/datacatalog_v1/data_catalog.rst | 10 - .../datacatalog_v1/policy_tag_manager.rst | 10 - .../policy_tag_manager_serialization.rst | 6 - .../v1/docs/datacatalog_v1/services.rst | 8 - .../v1/docs/datacatalog_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/datacatalog/__init__.py | 195 - .../v1/google/cloud/datacatalog/py.typed | 2 - .../google/cloud/datacatalog_v1/__init__.py | 196 - .../cloud/datacatalog_v1/gapic_metadata.json | 491 - .../v1/google/cloud/datacatalog_v1/py.typed | 2 - .../cloud/datacatalog_v1/services/__init__.py | 15 - .../services/data_catalog/__init__.py | 22 - .../services/data_catalog/async_client.py | 3009 ------ .../services/data_catalog/client.py | 3201 ------- .../services/data_catalog/pagers.py | 508 - .../data_catalog/transports/__init__.py | 33 - .../services/data_catalog/transports/base.py | 576 -- .../services/data_catalog/transports/grpc.py | 1161 --- .../data_catalog/transports/grpc_asyncio.py | 1165 --- .../services/policy_tag_manager/__init__.py | 22 - .../policy_tag_manager/async_client.py | 1300 --- .../services/policy_tag_manager/client.py | 1503 --- .../services/policy_tag_manager/pagers.py | 262 - .../policy_tag_manager/transports/__init__.py | 33 - .../policy_tag_manager/transports/base.py | 317 - .../policy_tag_manager/transports/grpc.py | 587 -- .../transports/grpc_asyncio.py | 591 -- .../__init__.py | 22 - .../async_client.py | 372 - .../client.py | 572 -- .../transports/__init__.py | 33 - .../transports/base.py | 175 - .../transports/grpc.py | 335 - .../transports/grpc_asyncio.py | 339 - .../cloud/datacatalog_v1/types/__init__.py | 205 - .../cloud/datacatalog_v1/types/bigquery.py | 115 - .../cloud/datacatalog_v1/types/common.py | 37 - .../cloud/datacatalog_v1/types/data_source.py | 56 - .../cloud/datacatalog_v1/types/datacatalog.py | 1578 ---- .../datacatalog_v1/types/gcs_fileset_spec.py | 115 - .../datacatalog_v1/types/policytagmanager.py | 495 - .../types/policytagmanagerserialization.py | 281 - .../cloud/datacatalog_v1/types/schema.py | 99 - .../cloud/datacatalog_v1/types/search.py | 164 - .../cloud/datacatalog_v1/types/table_spec.py | 161 - .../google/cloud/datacatalog_v1/types/tags.py | 458 - .../cloud/datacatalog_v1/types/timestamps.py | 67 - .../cloud/datacatalog_v1/types/usage.py | 103 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../scripts/fixup_datacatalog_v1_keywords.py | 216 - owl-bot-staging/v1/setup.py | 55 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/datacatalog_v1/__init__.py | 16 - .../gapic/datacatalog_v1/test_data_catalog.py | 8365 ----------------- .../datacatalog_v1/test_policy_tag_manager.py | 4247 --------- .../test_policy_tag_manager_serialization.py | 1379 --- owl-bot-staging/v1beta1/.coveragerc | 17 - owl-bot-staging/v1beta1/MANIFEST.in | 2 - owl-bot-staging/v1beta1/README.rst | 49 - owl-bot-staging/v1beta1/docs/conf.py | 376 - .../docs/datacatalog_v1beta1/data_catalog.rst | 10 - .../policy_tag_manager.rst | 10 - .../policy_tag_manager_serialization.rst | 6 - .../docs/datacatalog_v1beta1/services.rst | 8 - .../docs/datacatalog_v1beta1/types.rst | 7 - owl-bot-staging/v1beta1/docs/index.rst | 7 - .../google/cloud/datacatalog/__init__.py | 171 - .../v1beta1/google/cloud/datacatalog/py.typed | 2 - .../cloud/datacatalog_v1beta1/__init__.py | 172 - .../datacatalog_v1beta1/gapic_metadata.json | 471 - .../google/cloud/datacatalog_v1beta1/py.typed | 2 - .../datacatalog_v1beta1/services/__init__.py | 15 - .../services/data_catalog/__init__.py | 22 - .../services/data_catalog/async_client.py | 2878 ------ .../services/data_catalog/client.py | 3039 ------ .../services/data_catalog/pagers.py | 508 - .../data_catalog/transports/__init__.py | 33 - .../services/data_catalog/transports/base.py | 584 -- .../services/data_catalog/transports/grpc.py | 1079 --- .../data_catalog/transports/grpc_asyncio.py | 1083 --- .../services/policy_tag_manager/__init__.py | 22 - .../policy_tag_manager/async_client.py | 1263 --- .../services/policy_tag_manager/client.py | 1466 --- .../services/policy_tag_manager/pagers.py | 262 - .../policy_tag_manager/transports/__init__.py | 33 - .../policy_tag_manager/transports/base.py | 317 - .../policy_tag_manager/transports/grpc.py | 575 -- .../transports/grpc_asyncio.py | 579 -- .../__init__.py | 22 - .../async_client.py | 288 - .../client.py | 487 - .../transports/__init__.py | 33 - .../transports/base.py | 160 - .../transports/grpc.py | 290 - .../transports/grpc_asyncio.py | 294 - .../datacatalog_v1beta1/types/__init__.py | 175 - .../cloud/datacatalog_v1beta1/types/common.py | 36 - .../datacatalog_v1beta1/types/datacatalog.py | 1225 --- .../types/gcs_fileset_spec.py | 113 - .../types/policytagmanager.py | 449 - .../types/policytagmanagerserialization.py | 210 - .../cloud/datacatalog_v1beta1/types/schema.py | 89 - .../cloud/datacatalog_v1beta1/types/search.py | 88 - .../datacatalog_v1beta1/types/table_spec.py | 147 - .../cloud/datacatalog_v1beta1/types/tags.py | 384 - .../datacatalog_v1beta1/types/timestamps.py | 63 - owl-bot-staging/v1beta1/mypy.ini | 3 - owl-bot-staging/v1beta1/noxfile.py | 132 - .../fixup_datacatalog_v1beta1_keywords.py | 214 - owl-bot-staging/v1beta1/setup.py | 55 - owl-bot-staging/v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/datacatalog_v1beta1/__init__.py | 16 - .../datacatalog_v1beta1/test_data_catalog.py | 8035 ---------------- .../test_policy_tag_manager.py | 4233 --------- .../test_policy_tag_manager_serialization.py | 1210 --- 142 files changed, 62 insertions(+), 69558 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/conf.py delete mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst delete mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst delete mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst delete mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/datacatalog_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py delete mode 100644 owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.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_datacatalog_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/datacatalog_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py delete mode 100644 owl-bot-staging/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta1/README.rst delete mode 100644 owl-bot-staging/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst delete mode 100644 owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst delete mode 100644 owl-bot-staging/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py delete mode 100644 owl-bot-staging/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py delete mode 100644 owl-bot-staging/v1beta1/setup.py delete mode 100644 owl-bot-staging/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py diff --git a/google/cloud/datacatalog_v1/services/data_catalog/async_client.py b/google/cloud/datacatalog_v1/services/data_catalog/async_client.py index 14440363..72b33e0b 100644 --- a/google/cloud/datacatalog_v1/services/data_catalog/async_client.py +++ b/google/cloud/datacatalog_v1/services/data_catalog/async_client.py @@ -235,7 +235,7 @@ async def search_catalog( Optional. The query string with a minimum of 3 characters and specific syntax. For more information, see `Data Catalog search - syntax `__. + syntax `__. An empty query string returns all data assets (in the specified scope) that you have access to. @@ -1269,6 +1269,10 @@ async def list_entries( ) -> pagers.ListEntriesAsyncPager: r"""Lists entries. + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + Args: request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): The request object. Request message for @@ -1570,14 +1574,20 @@ async def update_tag_template( should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): Names of fields whose values to overwrite on a tag - template. Currently, only ``display_name`` can be - overwritten. + template. Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. If this parameter is absent or empty, all modifiable fields are overwritten. If such fields are non-required and omitted in the request body, their values are emptied. + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1964,7 +1974,7 @@ async def rename_tag_template_field( [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. name (:class:`str`): Required. The name of the tag - template. + template field. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/cloud/datacatalog_v1/services/data_catalog/client.py b/google/cloud/datacatalog_v1/services/data_catalog/client.py index cba5d7a5..2070ca22 100644 --- a/google/cloud/datacatalog_v1/services/data_catalog/client.py +++ b/google/cloud/datacatalog_v1/services/data_catalog/client.py @@ -505,7 +505,7 @@ def search_catalog( Optional. The query string with a minimum of 3 characters and specific syntax. For more information, see `Data Catalog search - syntax `__. + syntax `__. An empty query string returns all data assets (in the specified scope) that you have access to. @@ -1495,6 +1495,10 @@ def list_entries( ) -> pagers.ListEntriesPager: r"""Lists entries. + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + Args: request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): The request object. Request message for @@ -1787,14 +1791,20 @@ def update_tag_template( should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): Names of fields whose values to overwrite on a tag - template. Currently, only ``display_name`` can be - overwritten. + template. Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. If this parameter is absent or empty, all modifiable fields are overwritten. If such fields are non-required and omitted in the request body, their values are emptied. + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2185,7 +2195,7 @@ def rename_tag_template_field( [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. name (str): Required. The name of the tag - template. + template field. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py b/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py index 4ecaeb9b..7f088d80 100644 --- a/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py +++ b/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py @@ -608,6 +608,10 @@ def list_entries( Lists entries. + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + Returns: Callable[[~.ListEntriesRequest], ~.ListEntriesResponse]: diff --git a/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py b/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py index 9836b2a1..d589e7e9 100644 --- a/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py +++ b/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py @@ -621,6 +621,10 @@ def list_entries( Lists entries. + Note: Currently, this method can list only custom entries. To + get a list of both custom and automatically created entries, use + [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. + Returns: Callable[[~.ListEntriesRequest], Awaitable[~.ListEntriesResponse]]: diff --git a/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py b/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py index 9488330f..cb7aa44a 100644 --- a/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py +++ b/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py @@ -600,7 +600,7 @@ async def create_policy_tag( parent (:class:`str`): Required. Resource name of the taxonomy that the policy tag will belong - to.

+ to. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py b/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py index 8c3f131e..bdea63d3 100644 --- a/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py +++ b/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py @@ -805,7 +805,7 @@ def create_policy_tag( parent (str): Required. Resource name of the taxonomy that the policy tag will belong - to.

+ to. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/cloud/datacatalog_v1/types/bigquery.py b/google/cloud/datacatalog_v1/types/bigquery.py index 659b3f56..db9fef7b 100644 --- a/google/cloud/datacatalog_v1/types/bigquery.py +++ b/google/cloud/datacatalog_v1/types/bigquery.py @@ -37,7 +37,6 @@ class BigQueryConnectionSpec(proto.Message): cloud_sql (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec): Specification for the BigQuery connection to a Cloud SQL instance. - This field is a member of `oneof`_ ``connection_spec``. has_credential (bool): True if there are credentials attached to the diff --git a/google/cloud/datacatalog_v1/types/datacatalog.py b/google/cloud/datacatalog_v1/types/datacatalog.py index 3d77aab0..4ba1857b 100644 --- a/google/cloud/datacatalog_v1/types/datacatalog.py +++ b/google/cloud/datacatalog_v1/types/datacatalog.py @@ -102,7 +102,7 @@ class SearchCatalogRequest(proto.Message): Optional. The query string with a minimum of 3 characters and specific syntax. For more information, see `Data Catalog search - syntax `__. + syntax `__. An empty query string returns all data assets (in the specified scope) that you have access to. @@ -481,7 +481,6 @@ class LookupEntryRequest(proto.Message): - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` - ``//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}`` - This field is a member of `oneof`_ ``target_name``. sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. @@ -497,7 +496,6 @@ class LookupEntryRequest(proto.Message): Identifiers (``*_ID``) should comply with the [Lexical structure in Standard SQL] (https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical). - This field is a member of `oneof`_ ``target_name``. fully_qualified_name (str): Fully qualified name (FQN) of the resource. @@ -596,7 +594,6 @@ class Entry(proto.Message): Currently, only ``FILESET`` enum value is allowed. All other entries created in Data Catalog must use the ``user_specified_type``. - This field is a member of `oneof`_ ``entry_type``. user_specified_type (str): Custom entry type that doesn't match any of the values @@ -614,13 +611,11 @@ class Entry(proto.Message): - Can only contain letters, numbers, and underscores. - Must be at least 1 character and at most 64 characters long. - This field is a member of `oneof`_ ``entry_type``. integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): Output only. Indicates the entry's source system that Data Catalog integrates with, such as BigQuery, Pub/Sub, or Dataproc Metastore. - This field is a member of `oneof`_ ``system``. user_specified_system (str): Indicates the entry's source system that Data Catalog @@ -634,17 +629,14 @@ class Entry(proto.Message): - Can only contain letters, numbers, and underscores. - Must be at least 1 character and at most 64 characters long. - This field is a member of `oneof`_ ``system``. gcs_fileset_spec (google.cloud.datacatalog_v1.types.GcsFilesetSpec): Specification that applies to a Cloud Storage fileset. Valid only for entries with the ``FILESET`` type. - This field is a member of `oneof`_ ``type_spec``. bigquery_table_spec (google.cloud.datacatalog_v1.types.BigQueryTableSpec): Specification that applies to a BigQuery table. Valid only for entries with the ``TABLE`` type. - This field is a member of `oneof`_ ``type_spec``. bigquery_date_sharded_spec (google.cloud.datacatalog_v1.types.BigQueryDateShardedSpec): Specification for a group of BigQuery tables with the @@ -653,23 +645,19 @@ class Entry(proto.Message): For more information, see [Introduction to partitioned tables] (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). - This field is a member of `oneof`_ ``type_spec``. database_table_spec (google.cloud.datacatalog_v1.types.DatabaseTableSpec): Specification that applies to a table resource. Valid only for entries with the ``TABLE`` type. - This field is a member of `oneof`_ ``spec``. data_source_connection_spec (google.cloud.datacatalog_v1.types.DataSourceConnectionSpec): Specification that applies to a data source connection. Valid only for entries with the ``DATA_SOURCE_CONNECTION`` type. - This field is a member of `oneof`_ ``spec``. routine_spec (google.cloud.datacatalog_v1.types.RoutineSpec): Specification that applies to a user-defined function or procedure. Valid only for entries with the ``ROUTINE`` type. - This field is a member of `oneof`_ ``spec``. display_name (str): Display name of an entry. @@ -818,7 +806,6 @@ class RoutineSpec(proto.Message): The body of the routine. bigquery_routine_spec (google.cloud.datacatalog_v1.types.BigQueryRoutineSpec): Fields specific for BigQuery routines. - This field is a member of `oneof`_ ``system_spec``. """ @@ -950,11 +937,18 @@ class UpdateTagTemplateRequest(proto.Message): set. update_mask (google.protobuf.field_mask_pb2.FieldMask): Names of fields whose values to overwrite on a tag template. - Currently, only ``display_name`` can be overwritten. + Currently, only ``display_name`` and + ``is_publicly_readable`` can be overwritten. If this parameter is absent or empty, all modifiable fields are overwritten. If such fields are non-required and omitted in the request body, their values are emptied. + + Note: Updating the ``is_publicly_readable`` field may + require up to 12 hours to take effect in search results. + Additionally, it also requires the + ``tagTemplates.getIamPolicy`` and + ``tagTemplates.setIamPolicy`` permissions. """ tag_template = proto.Field(proto.MESSAGE, number=1, message=gcd_tags.TagTemplate,) @@ -1114,7 +1108,7 @@ class RenameTagTemplateFieldRequest(proto.Message): Attributes: name (str): - Required. The name of the tag template. + Required. The name of the tag template field. new_tag_template_field_id (str): Required. The new ID of this tag template field. For example, ``my_new_field``. diff --git a/google/cloud/datacatalog_v1/types/policytagmanager.py b/google/cloud/datacatalog_v1/types/policytagmanager.py index 623a0af2..036d6db1 100644 --- a/google/cloud/datacatalog_v1/types/policytagmanager.py +++ b/google/cloud/datacatalog_v1/types/policytagmanager.py @@ -131,7 +131,7 @@ class PolicyTag(proto.Message): Output only. Resource name of this policy tag in the URL format. The policy tag manager generates unique taxonomy - IDs and policy tag IDs.

+ IDs and policy tag IDs. display_name (str): Required. User-defined name of this policy tag. @@ -285,7 +285,7 @@ class CreatePolicyTagRequest(proto.Message): Attributes: parent (str): Required. Resource name of the taxonomy that - the policy tag will belong to.

+ the policy tag will belong to. policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): The policy tag to create. """ diff --git a/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py b/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py index f234e43e..9fc96f42 100644 --- a/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py +++ b/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py @@ -129,11 +129,9 @@ class ImportTaxonomiesRequest(proto.Message): imported taxonomies will belong to. inline_source (google.cloud.datacatalog_v1.types.InlineSource): Inline source taxonomy to import. - This field is a member of `oneof`_ ``source``. cross_regional_source (google.cloud.datacatalog_v1.types.CrossRegionalSource): Cross-regional source taxonomy to import. - This field is a member of `oneof`_ ``source``. """ @@ -203,7 +201,6 @@ class ExportTaxonomiesRequest(proto.Message): serialized_taxonomies (bool): Serialized export taxonomies that contain all the policy tags as nested protocol buffers. - This field is a member of `oneof`_ ``destination``. """ diff --git a/google/cloud/datacatalog_v1/types/search.py b/google/cloud/datacatalog_v1/types/search.py index 186475ee..393e7902 100644 --- a/google/cloud/datacatalog_v1/types/search.py +++ b/google/cloud/datacatalog_v1/types/search.py @@ -82,12 +82,10 @@ class SearchCatalogResult(proto.Message): Output only. The source system that Data Catalog automatically integrates with, such as BigQuery, Cloud Pub/Sub, or Dataproc Metastore. - This field is a member of `oneof`_ ``system``. user_specified_system (str): Custom source system that you can manually integrate Data Catalog with. - This field is a member of `oneof`_ ``system``. fully_qualified_name (str): Fully qualified name (FQN) of the resource. @@ -105,6 +103,12 @@ class SearchCatalogResult(proto.Message): Example for a DPMS table: ``dataproc_metastore:PROJECT_ID.LOCATION_ID.INSTANCE_ID.DATABASE_ID.TABLE_ID`` + display_name (str): + The display name of the result. + description (str): + Entry description that can consist of several + sentences or paragraphs that describe entry + contents. """ search_result_type = proto.Field(proto.ENUM, number=1, enum="SearchResultType",) @@ -117,6 +121,8 @@ class SearchCatalogResult(proto.Message): ) user_specified_system = proto.Field(proto.STRING, number=9, oneof="system",) fully_qualified_name = proto.Field(proto.STRING, number=10,) + display_name = proto.Field(proto.STRING, number=12,) + description = proto.Field(proto.STRING, number=13,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/datacatalog_v1/types/table_spec.py b/google/cloud/datacatalog_v1/types/table_spec.py index 295dc842..83b11fd2 100644 --- a/google/cloud/datacatalog_v1/types/table_spec.py +++ b/google/cloud/datacatalog_v1/types/table_spec.py @@ -52,12 +52,10 @@ class BigQueryTableSpec(proto.Message): view_spec (google.cloud.datacatalog_v1.types.ViewSpec): Table view specification. Populated only if the ``table_source_type`` is ``BIGQUERY_VIEW``. - This field is a member of `oneof`_ ``type_spec``. table_spec (google.cloud.datacatalog_v1.types.TableSpec): Specification of a BigQuery table. Populated only if the ``table_source_type`` is ``BIGQUERY_TABLE``. - This field is a member of `oneof`_ ``type_spec``. """ @@ -121,11 +119,15 @@ class BigQueryDateShardedSpec(proto.Message): ``table_prefix`` is ``MyTable``. shard_count (int): Output only. Total number of shards. + latest_shard_resource (str): + Output only. BigQuery resource name of the + latest shard. """ dataset = proto.Field(proto.STRING, number=1,) table_prefix = proto.Field(proto.STRING, number=2,) shard_count = proto.Field(proto.INT64, number=3,) + latest_shard_resource = proto.Field(proto.STRING, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/datacatalog_v1/types/tags.py b/google/cloud/datacatalog_v1/types/tags.py index 8b5b34e9..912b9744 100644 --- a/google/cloud/datacatalog_v1/types/tags.py +++ b/google/cloud/datacatalog_v1/types/tags.py @@ -59,7 +59,6 @@ class Tag(proto.Message): To attach a tag to a nested column, separate column names with a dot (``.``). Example: ``column.nested_column``. - This field is a member of `oneof`_ ``scope``. fields (Sequence[google.cloud.datacatalog_v1.types.Tag.FieldsEntry]): Required. Maps the ID of a tag field to its @@ -93,27 +92,22 @@ class TagField(proto.Message): Output only. The display name of this field. double_value (float): The value of a tag field with a double type. - This field is a member of `oneof`_ ``kind``. string_value (str): The value of a tag field with a string type. The maximum length is 2000 UTF-8 characters. - This field is a member of `oneof`_ ``kind``. bool_value (bool): The value of a tag field with a boolean type. - This field is a member of `oneof`_ ``kind``. timestamp_value (google.protobuf.timestamp_pb2.Timestamp): The value of a tag field with a timestamp type. - This field is a member of `oneof`_ ``kind``. enum_value (google.cloud.datacatalog_v1.types.TagField.EnumValue): The value of a tag field with an enum type. This value must be one of the allowed values listed in this enum. - This field is a member of `oneof`_ ``kind``. richtext_value (str): The value of a tag field with a rich text @@ -122,7 +116,6 @@ class TagField(proto.Message): HTML descriptions including encoded images. The maximum length of the text without images is 100 KiB. - This field is a member of `oneof`_ ``kind``. order (int): Output only. The order of this field with respect to other @@ -304,11 +297,9 @@ class FieldType(proto.Message): primitive_type (google.cloud.datacatalog_v1.types.FieldType.PrimitiveType): Primitive types, such as string, boolean, etc. - This field is a member of `oneof`_ ``type_decl``. enum_type (google.cloud.datacatalog_v1.types.FieldType.EnumType): An enum type. - This field is a member of `oneof`_ ``type_decl``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/datacatalog.py b/google/cloud/datacatalog_v1beta1/types/datacatalog.py index 7d8d7eec..26da6f59 100644 --- a/google/cloud/datacatalog_v1beta1/types/datacatalog.py +++ b/google/cloud/datacatalog_v1beta1/types/datacatalog.py @@ -425,7 +425,6 @@ class LookupEntryRequest(proto.Message): - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId - //pubsub.googleapis.com/projects/projectId/topics/topicId - This field is a member of `oneof`_ ``target_name``. sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. @@ -441,7 +440,6 @@ class LookupEntryRequest(proto.Message): ``*_id``\ s shoud satisfy the standard SQL rules for identifiers. https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. - This field is a member of `oneof`_ ``target_name``. """ @@ -494,7 +492,6 @@ class Entry(proto.Message): The type of the entry. Only used for Entries with types in the EntryType enum. - This field is a member of `oneof`_ ``entry_type``. user_specified_type (str): Entry type if it does not fit any of the input-allowed @@ -510,13 +507,11 @@ class Entry(proto.Message): Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use ``user_specified_type``. - This field is a member of `oneof`_ ``entry_type``. integrated_system (google.cloud.datacatalog_v1beta1.types.IntegratedSystem): Output only. This field indicates the entry's source system that Data Catalog integrates with, such as BigQuery or Pub/Sub. - This field is a member of `oneof`_ ``system``. user_specified_system (str): This field indicates the entry's source system that Data @@ -525,24 +520,20 @@ class Entry(proto.Message): contain letters, numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. - This field is a member of `oneof`_ ``system``. gcs_fileset_spec (google.cloud.datacatalog_v1beta1.types.GcsFilesetSpec): Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. - This field is a member of `oneof`_ ``type_spec``. bigquery_table_spec (google.cloud.datacatalog_v1beta1.types.BigQueryTableSpec): Specification that applies to a BigQuery table. This is only valid on entries of type ``TABLE``. - This field is a member of `oneof`_ ``type_spec``. bigquery_date_sharded_spec (google.cloud.datacatalog_v1beta1.types.BigQueryDateShardedSpec): Specification for a group of BigQuery tables with name pattern ``[prefix]YYYYMMDD``. Context: https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. - This field is a member of `oneof`_ ``type_spec``. display_name (str): Display information such as title and diff --git a/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py b/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py index f8353ee4..87aab667 100644 --- a/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py +++ b/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py @@ -146,7 +146,6 @@ class ExportTaxonomiesRequest(proto.Message): be exported. serialized_taxonomies (bool): Export taxonomies as serialized taxonomies. - This field is a member of `oneof`_ ``destination``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/table_spec.py b/google/cloud/datacatalog_v1beta1/types/table_spec.py index 005276a4..dd7489fa 100644 --- a/google/cloud/datacatalog_v1beta1/types/table_spec.py +++ b/google/cloud/datacatalog_v1beta1/types/table_spec.py @@ -51,12 +51,10 @@ class BigQueryTableSpec(proto.Message): view_spec (google.cloud.datacatalog_v1beta1.types.ViewSpec): Table view specification. This field should only be populated if ``table_source_type`` is ``BIGQUERY_VIEW``. - This field is a member of `oneof`_ ``type_spec``. table_spec (google.cloud.datacatalog_v1beta1.types.TableSpec): Spec of a BigQuery table. This field should only be populated if ``table_source_type`` is ``BIGQUERY_TABLE``. - This field is a member of `oneof`_ ``type_spec``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/tags.py b/google/cloud/datacatalog_v1beta1/types/tags.py index 3f9d384f..a556873a 100644 --- a/google/cloud/datacatalog_v1beta1/types/tags.py +++ b/google/cloud/datacatalog_v1beta1/types/tags.py @@ -63,7 +63,6 @@ class Tag(proto.Message): separate the column names. Example: - ``outer_column.inner_column`` - This field is a member of `oneof`_ ``scope``. fields (Sequence[google.cloud.datacatalog_v1beta1.types.Tag.FieldsEntry]): Required. This maps the ID of a tag field to @@ -97,28 +96,23 @@ class TagField(proto.Message): double_value (float): Holds the value for a tag field with double type. - This field is a member of `oneof`_ ``kind``. string_value (str): Holds the value for a tag field with string type. - This field is a member of `oneof`_ ``kind``. bool_value (bool): Holds the value for a tag field with boolean type. - This field is a member of `oneof`_ ``kind``. timestamp_value (google.protobuf.timestamp_pb2.Timestamp): Holds the value for a tag field with timestamp type. - This field is a member of `oneof`_ ``kind``. enum_value (google.cloud.datacatalog_v1beta1.types.TagField.EnumValue): Holds the value for a tag field with enum type. This value must be one of the allowed values in the definition of this enum. - This field is a member of `oneof`_ ``kind``. order (int): Output only. The order of this field with respect to other @@ -245,11 +239,9 @@ class FieldType(proto.Message): primitive_type (google.cloud.datacatalog_v1beta1.types.FieldType.PrimitiveType): Represents primitive types - string, bool etc. - This field is a member of `oneof`_ ``type_decl``. enum_type (google.cloud.datacatalog_v1beta1.types.FieldType.EnumType): Represents an enum type. - This field is a member of `oneof`_ ``type_decl``. """ diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index ac5fa2e9..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/datacatalog/__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 7344043d..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/datacatalog *.py -recursive-include google/cloud/datacatalog_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 8f53b244..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Datacatalog 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 Datacatalog API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 67b364b2..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-datacatalog 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-datacatalog" -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-datacatalog-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-datacatalog.tex", - u"google-cloud-datacatalog 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-datacatalog", - u"Google Cloud Datacatalog 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-datacatalog", - u"google-cloud-datacatalog Documentation", - author, - "google-cloud-datacatalog", - "GAPIC library for Google Cloud Datacatalog 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/datacatalog_v1/data_catalog.rst b/owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst deleted file mode 100644 index 6141a1c7..00000000 --- a/owl-bot-staging/v1/docs/datacatalog_v1/data_catalog.rst +++ /dev/null @@ -1,10 +0,0 @@ -DataCatalog ------------------------------ - -.. automodule:: google.cloud.datacatalog_v1.services.data_catalog - :members: - :inherited-members: - -.. automodule:: google.cloud.datacatalog_v1.services.data_catalog.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst deleted file mode 100644 index 03d2846f..00000000 --- a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager.rst +++ /dev/null @@ -1,10 +0,0 @@ -PolicyTagManager ----------------------------------- - -.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager - :members: - :inherited-members: - -.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst b/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst deleted file mode 100644 index f7006d1b..00000000 --- a/owl-bot-staging/v1/docs/datacatalog_v1/policy_tag_manager_serialization.rst +++ /dev/null @@ -1,6 +0,0 @@ -PolicyTagManagerSerialization ------------------------------------------------ - -.. automodule:: google.cloud.datacatalog_v1.services.policy_tag_manager_serialization - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/services.rst b/owl-bot-staging/v1/docs/datacatalog_v1/services.rst deleted file mode 100644 index a70d3132..00000000 --- a/owl-bot-staging/v1/docs/datacatalog_v1/services.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Cloud Datacatalog v1 API -============================================ -.. toctree:: - :maxdepth: 2 - - data_catalog - policy_tag_manager - policy_tag_manager_serialization diff --git a/owl-bot-staging/v1/docs/datacatalog_v1/types.rst b/owl-bot-staging/v1/docs/datacatalog_v1/types.rst deleted file mode 100644 index a27783ee..00000000 --- a/owl-bot-staging/v1/docs/datacatalog_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Datacatalog v1 API -========================================= - -.. automodule:: google.cloud.datacatalog_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 7af52885..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - datacatalog_v1/services - datacatalog_v1/types diff --git a/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py deleted file mode 100644 index 41e4328e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog/__init__.py +++ /dev/null @@ -1,195 +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.datacatalog_v1.services.data_catalog.client import DataCatalogClient -from google.cloud.datacatalog_v1.services.data_catalog.async_client import DataCatalogAsyncClient -from google.cloud.datacatalog_v1.services.policy_tag_manager.client import PolicyTagManagerClient -from google.cloud.datacatalog_v1.services.policy_tag_manager.async_client import PolicyTagManagerAsyncClient -from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.client import PolicyTagManagerSerializationClient -from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.async_client import PolicyTagManagerSerializationAsyncClient - -from google.cloud.datacatalog_v1.types.bigquery import BigQueryConnectionSpec -from google.cloud.datacatalog_v1.types.bigquery import BigQueryRoutineSpec -from google.cloud.datacatalog_v1.types.bigquery import CloudSqlBigQueryConnectionSpec -from google.cloud.datacatalog_v1.types.common import IntegratedSystem -from google.cloud.datacatalog_v1.types.data_source import DataSource -from google.cloud.datacatalog_v1.types.datacatalog import CreateEntryGroupRequest -from google.cloud.datacatalog_v1.types.datacatalog import CreateEntryRequest -from google.cloud.datacatalog_v1.types.datacatalog import CreateTagRequest -from google.cloud.datacatalog_v1.types.datacatalog import CreateTagTemplateFieldRequest -from google.cloud.datacatalog_v1.types.datacatalog import CreateTagTemplateRequest -from google.cloud.datacatalog_v1.types.datacatalog import DatabaseTableSpec -from google.cloud.datacatalog_v1.types.datacatalog import DataSourceConnectionSpec -from google.cloud.datacatalog_v1.types.datacatalog import DeleteEntryGroupRequest -from google.cloud.datacatalog_v1.types.datacatalog import DeleteEntryRequest -from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagRequest -from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagTemplateFieldRequest -from google.cloud.datacatalog_v1.types.datacatalog import DeleteTagTemplateRequest -from google.cloud.datacatalog_v1.types.datacatalog import Entry -from google.cloud.datacatalog_v1.types.datacatalog import EntryGroup -from google.cloud.datacatalog_v1.types.datacatalog import GetEntryGroupRequest -from google.cloud.datacatalog_v1.types.datacatalog import GetEntryRequest -from google.cloud.datacatalog_v1.types.datacatalog import GetTagTemplateRequest -from google.cloud.datacatalog_v1.types.datacatalog import ListEntriesRequest -from google.cloud.datacatalog_v1.types.datacatalog import ListEntriesResponse -from google.cloud.datacatalog_v1.types.datacatalog import ListEntryGroupsRequest -from google.cloud.datacatalog_v1.types.datacatalog import ListEntryGroupsResponse -from google.cloud.datacatalog_v1.types.datacatalog import ListTagsRequest -from google.cloud.datacatalog_v1.types.datacatalog import ListTagsResponse -from google.cloud.datacatalog_v1.types.datacatalog import LookupEntryRequest -from google.cloud.datacatalog_v1.types.datacatalog import RenameTagTemplateFieldEnumValueRequest -from google.cloud.datacatalog_v1.types.datacatalog import RenameTagTemplateFieldRequest -from google.cloud.datacatalog_v1.types.datacatalog import RoutineSpec -from google.cloud.datacatalog_v1.types.datacatalog import SearchCatalogRequest -from google.cloud.datacatalog_v1.types.datacatalog import SearchCatalogResponse -from google.cloud.datacatalog_v1.types.datacatalog import UpdateEntryGroupRequest -from google.cloud.datacatalog_v1.types.datacatalog import UpdateEntryRequest -from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagRequest -from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagTemplateFieldRequest -from google.cloud.datacatalog_v1.types.datacatalog import UpdateTagTemplateRequest -from google.cloud.datacatalog_v1.types.datacatalog import EntryType -from google.cloud.datacatalog_v1.types.gcs_fileset_spec import GcsFilesetSpec -from google.cloud.datacatalog_v1.types.gcs_fileset_spec import GcsFileSpec -from google.cloud.datacatalog_v1.types.policytagmanager import CreatePolicyTagRequest -from google.cloud.datacatalog_v1.types.policytagmanager import CreateTaxonomyRequest -from google.cloud.datacatalog_v1.types.policytagmanager import DeletePolicyTagRequest -from google.cloud.datacatalog_v1.types.policytagmanager import DeleteTaxonomyRequest -from google.cloud.datacatalog_v1.types.policytagmanager import GetPolicyTagRequest -from google.cloud.datacatalog_v1.types.policytagmanager import GetTaxonomyRequest -from google.cloud.datacatalog_v1.types.policytagmanager import ListPolicyTagsRequest -from google.cloud.datacatalog_v1.types.policytagmanager import ListPolicyTagsResponse -from google.cloud.datacatalog_v1.types.policytagmanager import ListTaxonomiesRequest -from google.cloud.datacatalog_v1.types.policytagmanager import ListTaxonomiesResponse -from google.cloud.datacatalog_v1.types.policytagmanager import PolicyTag -from google.cloud.datacatalog_v1.types.policytagmanager import Taxonomy -from google.cloud.datacatalog_v1.types.policytagmanager import UpdatePolicyTagRequest -from google.cloud.datacatalog_v1.types.policytagmanager import UpdateTaxonomyRequest -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import CrossRegionalSource -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ExportTaxonomiesRequest -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ExportTaxonomiesResponse -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ImportTaxonomiesRequest -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ImportTaxonomiesResponse -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import InlineSource -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import ReplaceTaxonomyRequest -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import SerializedPolicyTag -from google.cloud.datacatalog_v1.types.policytagmanagerserialization import SerializedTaxonomy -from google.cloud.datacatalog_v1.types.schema import ColumnSchema -from google.cloud.datacatalog_v1.types.schema import Schema -from google.cloud.datacatalog_v1.types.search import SearchCatalogResult -from google.cloud.datacatalog_v1.types.search import SearchResultType -from google.cloud.datacatalog_v1.types.table_spec import BigQueryDateShardedSpec -from google.cloud.datacatalog_v1.types.table_spec import BigQueryTableSpec -from google.cloud.datacatalog_v1.types.table_spec import TableSpec -from google.cloud.datacatalog_v1.types.table_spec import ViewSpec -from google.cloud.datacatalog_v1.types.table_spec import TableSourceType -from google.cloud.datacatalog_v1.types.tags import FieldType -from google.cloud.datacatalog_v1.types.tags import Tag -from google.cloud.datacatalog_v1.types.tags import TagField -from google.cloud.datacatalog_v1.types.tags import TagTemplate -from google.cloud.datacatalog_v1.types.tags import TagTemplateField -from google.cloud.datacatalog_v1.types.timestamps import SystemTimestamps -from google.cloud.datacatalog_v1.types.usage import UsageSignal -from google.cloud.datacatalog_v1.types.usage import UsageStats - -__all__ = ('DataCatalogClient', - 'DataCatalogAsyncClient', - 'PolicyTagManagerClient', - 'PolicyTagManagerAsyncClient', - 'PolicyTagManagerSerializationClient', - 'PolicyTagManagerSerializationAsyncClient', - 'BigQueryConnectionSpec', - 'BigQueryRoutineSpec', - 'CloudSqlBigQueryConnectionSpec', - 'IntegratedSystem', - 'DataSource', - 'CreateEntryGroupRequest', - 'CreateEntryRequest', - 'CreateTagRequest', - 'CreateTagTemplateFieldRequest', - 'CreateTagTemplateRequest', - 'DatabaseTableSpec', - 'DataSourceConnectionSpec', - 'DeleteEntryGroupRequest', - 'DeleteEntryRequest', - 'DeleteTagRequest', - 'DeleteTagTemplateFieldRequest', - 'DeleteTagTemplateRequest', - 'Entry', - 'EntryGroup', - 'GetEntryGroupRequest', - 'GetEntryRequest', - 'GetTagTemplateRequest', - 'ListEntriesRequest', - 'ListEntriesResponse', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'ListTagsRequest', - 'ListTagsResponse', - 'LookupEntryRequest', - 'RenameTagTemplateFieldEnumValueRequest', - 'RenameTagTemplateFieldRequest', - 'RoutineSpec', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'UpdateEntryGroupRequest', - 'UpdateEntryRequest', - 'UpdateTagRequest', - 'UpdateTagTemplateFieldRequest', - 'UpdateTagTemplateRequest', - 'EntryType', - 'GcsFilesetSpec', - 'GcsFileSpec', - 'CreatePolicyTagRequest', - 'CreateTaxonomyRequest', - 'DeletePolicyTagRequest', - 'DeleteTaxonomyRequest', - 'GetPolicyTagRequest', - 'GetTaxonomyRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'PolicyTag', - 'Taxonomy', - 'UpdatePolicyTagRequest', - 'UpdateTaxonomyRequest', - 'CrossRegionalSource', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - 'ImportTaxonomiesRequest', - 'ImportTaxonomiesResponse', - 'InlineSource', - 'ReplaceTaxonomyRequest', - 'SerializedPolicyTag', - 'SerializedTaxonomy', - 'ColumnSchema', - 'Schema', - 'SearchCatalogResult', - 'SearchResultType', - 'BigQueryDateShardedSpec', - 'BigQueryTableSpec', - 'TableSpec', - 'ViewSpec', - 'TableSourceType', - 'FieldType', - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'SystemTimestamps', - 'UsageSignal', - 'UsageStats', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog/py.typed b/owl-bot-staging/v1/google/cloud/datacatalog/py.typed deleted file mode 100644 index bb4088a3..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py deleted file mode 100644 index bd45c6c1..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/__init__.py +++ /dev/null @@ -1,196 +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_catalog import DataCatalogClient -from .services.data_catalog import DataCatalogAsyncClient -from .services.policy_tag_manager import PolicyTagManagerClient -from .services.policy_tag_manager import PolicyTagManagerAsyncClient -from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient -from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient - -from .types.bigquery import BigQueryConnectionSpec -from .types.bigquery import BigQueryRoutineSpec -from .types.bigquery import CloudSqlBigQueryConnectionSpec -from .types.common import IntegratedSystem -from .types.data_source import DataSource -from .types.datacatalog import CreateEntryGroupRequest -from .types.datacatalog import CreateEntryRequest -from .types.datacatalog import CreateTagRequest -from .types.datacatalog import CreateTagTemplateFieldRequest -from .types.datacatalog import CreateTagTemplateRequest -from .types.datacatalog import DatabaseTableSpec -from .types.datacatalog import DataSourceConnectionSpec -from .types.datacatalog import DeleteEntryGroupRequest -from .types.datacatalog import DeleteEntryRequest -from .types.datacatalog import DeleteTagRequest -from .types.datacatalog import DeleteTagTemplateFieldRequest -from .types.datacatalog import DeleteTagTemplateRequest -from .types.datacatalog import Entry -from .types.datacatalog import EntryGroup -from .types.datacatalog import GetEntryGroupRequest -from .types.datacatalog import GetEntryRequest -from .types.datacatalog import GetTagTemplateRequest -from .types.datacatalog import ListEntriesRequest -from .types.datacatalog import ListEntriesResponse -from .types.datacatalog import ListEntryGroupsRequest -from .types.datacatalog import ListEntryGroupsResponse -from .types.datacatalog import ListTagsRequest -from .types.datacatalog import ListTagsResponse -from .types.datacatalog import LookupEntryRequest -from .types.datacatalog import RenameTagTemplateFieldEnumValueRequest -from .types.datacatalog import RenameTagTemplateFieldRequest -from .types.datacatalog import RoutineSpec -from .types.datacatalog import SearchCatalogRequest -from .types.datacatalog import SearchCatalogResponse -from .types.datacatalog import UpdateEntryGroupRequest -from .types.datacatalog import UpdateEntryRequest -from .types.datacatalog import UpdateTagRequest -from .types.datacatalog import UpdateTagTemplateFieldRequest -from .types.datacatalog import UpdateTagTemplateRequest -from .types.datacatalog import EntryType -from .types.gcs_fileset_spec import GcsFilesetSpec -from .types.gcs_fileset_spec import GcsFileSpec -from .types.policytagmanager import CreatePolicyTagRequest -from .types.policytagmanager import CreateTaxonomyRequest -from .types.policytagmanager import DeletePolicyTagRequest -from .types.policytagmanager import DeleteTaxonomyRequest -from .types.policytagmanager import GetPolicyTagRequest -from .types.policytagmanager import GetTaxonomyRequest -from .types.policytagmanager import ListPolicyTagsRequest -from .types.policytagmanager import ListPolicyTagsResponse -from .types.policytagmanager import ListTaxonomiesRequest -from .types.policytagmanager import ListTaxonomiesResponse -from .types.policytagmanager import PolicyTag -from .types.policytagmanager import Taxonomy -from .types.policytagmanager import UpdatePolicyTagRequest -from .types.policytagmanager import UpdateTaxonomyRequest -from .types.policytagmanagerserialization import CrossRegionalSource -from .types.policytagmanagerserialization import ExportTaxonomiesRequest -from .types.policytagmanagerserialization import ExportTaxonomiesResponse -from .types.policytagmanagerserialization import ImportTaxonomiesRequest -from .types.policytagmanagerserialization import ImportTaxonomiesResponse -from .types.policytagmanagerserialization import InlineSource -from .types.policytagmanagerserialization import ReplaceTaxonomyRequest -from .types.policytagmanagerserialization import SerializedPolicyTag -from .types.policytagmanagerserialization import SerializedTaxonomy -from .types.schema import ColumnSchema -from .types.schema import Schema -from .types.search import SearchCatalogResult -from .types.search import SearchResultType -from .types.table_spec import BigQueryDateShardedSpec -from .types.table_spec import BigQueryTableSpec -from .types.table_spec import TableSpec -from .types.table_spec import ViewSpec -from .types.table_spec import TableSourceType -from .types.tags import FieldType -from .types.tags import Tag -from .types.tags import TagField -from .types.tags import TagTemplate -from .types.tags import TagTemplateField -from .types.timestamps import SystemTimestamps -from .types.usage import UsageSignal -from .types.usage import UsageStats - -__all__ = ( - 'DataCatalogAsyncClient', - 'PolicyTagManagerAsyncClient', - 'PolicyTagManagerSerializationAsyncClient', -'BigQueryConnectionSpec', -'BigQueryDateShardedSpec', -'BigQueryRoutineSpec', -'BigQueryTableSpec', -'CloudSqlBigQueryConnectionSpec', -'ColumnSchema', -'CreateEntryGroupRequest', -'CreateEntryRequest', -'CreatePolicyTagRequest', -'CreateTagRequest', -'CreateTagTemplateFieldRequest', -'CreateTagTemplateRequest', -'CreateTaxonomyRequest', -'CrossRegionalSource', -'DataCatalogClient', -'DataSource', -'DataSourceConnectionSpec', -'DatabaseTableSpec', -'DeleteEntryGroupRequest', -'DeleteEntryRequest', -'DeletePolicyTagRequest', -'DeleteTagRequest', -'DeleteTagTemplateFieldRequest', -'DeleteTagTemplateRequest', -'DeleteTaxonomyRequest', -'Entry', -'EntryGroup', -'EntryType', -'ExportTaxonomiesRequest', -'ExportTaxonomiesResponse', -'FieldType', -'GcsFileSpec', -'GcsFilesetSpec', -'GetEntryGroupRequest', -'GetEntryRequest', -'GetPolicyTagRequest', -'GetTagTemplateRequest', -'GetTaxonomyRequest', -'ImportTaxonomiesRequest', -'ImportTaxonomiesResponse', -'InlineSource', -'IntegratedSystem', -'ListEntriesRequest', -'ListEntriesResponse', -'ListEntryGroupsRequest', -'ListEntryGroupsResponse', -'ListPolicyTagsRequest', -'ListPolicyTagsResponse', -'ListTagsRequest', -'ListTagsResponse', -'ListTaxonomiesRequest', -'ListTaxonomiesResponse', -'LookupEntryRequest', -'PolicyTag', -'PolicyTagManagerClient', -'PolicyTagManagerSerializationClient', -'RenameTagTemplateFieldEnumValueRequest', -'RenameTagTemplateFieldRequest', -'ReplaceTaxonomyRequest', -'RoutineSpec', -'Schema', -'SearchCatalogRequest', -'SearchCatalogResponse', -'SearchCatalogResult', -'SearchResultType', -'SerializedPolicyTag', -'SerializedTaxonomy', -'SystemTimestamps', -'TableSourceType', -'TableSpec', -'Tag', -'TagField', -'TagTemplate', -'TagTemplateField', -'Taxonomy', -'UpdateEntryGroupRequest', -'UpdateEntryRequest', -'UpdatePolicyTagRequest', -'UpdateTagRequest', -'UpdateTagTemplateFieldRequest', -'UpdateTagTemplateRequest', -'UpdateTaxonomyRequest', -'UsageSignal', -'UsageStats', -'ViewSpec', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json deleted file mode 100644 index 99e0398a..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/gapic_metadata.json +++ /dev/null @@ -1,491 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.datacatalog_v1", - "protoPackage": "google.cloud.datacatalog.v1", - "schema": "1.0", - "services": { - "DataCatalog": { - "clients": { - "grpc": { - "libraryClient": "DataCatalogClient", - "rpcs": { - "CreateEntry": { - "methods": [ - "create_entry" - ] - }, - "CreateEntryGroup": { - "methods": [ - "create_entry_group" - ] - }, - "CreateTag": { - "methods": [ - "create_tag" - ] - }, - "CreateTagTemplate": { - "methods": [ - "create_tag_template" - ] - }, - "CreateTagTemplateField": { - "methods": [ - "create_tag_template_field" - ] - }, - "DeleteEntry": { - "methods": [ - "delete_entry" - ] - }, - "DeleteEntryGroup": { - "methods": [ - "delete_entry_group" - ] - }, - "DeleteTag": { - "methods": [ - "delete_tag" - ] - }, - "DeleteTagTemplate": { - "methods": [ - "delete_tag_template" - ] - }, - "DeleteTagTemplateField": { - "methods": [ - "delete_tag_template_field" - ] - }, - "GetEntry": { - "methods": [ - "get_entry" - ] - }, - "GetEntryGroup": { - "methods": [ - "get_entry_group" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagTemplate": { - "methods": [ - "get_tag_template" - ] - }, - "ListEntries": { - "methods": [ - "list_entries" - ] - }, - "ListEntryGroups": { - "methods": [ - "list_entry_groups" - ] - }, - "ListTags": { - "methods": [ - "list_tags" - ] - }, - "LookupEntry": { - "methods": [ - "lookup_entry" - ] - }, - "RenameTagTemplateField": { - "methods": [ - "rename_tag_template_field" - ] - }, - "RenameTagTemplateFieldEnumValue": { - "methods": [ - "rename_tag_template_field_enum_value" - ] - }, - "SearchCatalog": { - "methods": [ - "search_catalog" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEntry": { - "methods": [ - "update_entry" - ] - }, - "UpdateEntryGroup": { - "methods": [ - "update_entry_group" - ] - }, - "UpdateTag": { - "methods": [ - "update_tag" - ] - }, - "UpdateTagTemplate": { - "methods": [ - "update_tag_template" - ] - }, - "UpdateTagTemplateField": { - "methods": [ - "update_tag_template_field" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataCatalogAsyncClient", - "rpcs": { - "CreateEntry": { - "methods": [ - "create_entry" - ] - }, - "CreateEntryGroup": { - "methods": [ - "create_entry_group" - ] - }, - "CreateTag": { - "methods": [ - "create_tag" - ] - }, - "CreateTagTemplate": { - "methods": [ - "create_tag_template" - ] - }, - "CreateTagTemplateField": { - "methods": [ - "create_tag_template_field" - ] - }, - "DeleteEntry": { - "methods": [ - "delete_entry" - ] - }, - "DeleteEntryGroup": { - "methods": [ - "delete_entry_group" - ] - }, - "DeleteTag": { - "methods": [ - "delete_tag" - ] - }, - "DeleteTagTemplate": { - "methods": [ - "delete_tag_template" - ] - }, - "DeleteTagTemplateField": { - "methods": [ - "delete_tag_template_field" - ] - }, - "GetEntry": { - "methods": [ - "get_entry" - ] - }, - "GetEntryGroup": { - "methods": [ - "get_entry_group" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagTemplate": { - "methods": [ - "get_tag_template" - ] - }, - "ListEntries": { - "methods": [ - "list_entries" - ] - }, - "ListEntryGroups": { - "methods": [ - "list_entry_groups" - ] - }, - "ListTags": { - "methods": [ - "list_tags" - ] - }, - "LookupEntry": { - "methods": [ - "lookup_entry" - ] - }, - "RenameTagTemplateField": { - "methods": [ - "rename_tag_template_field" - ] - }, - "RenameTagTemplateFieldEnumValue": { - "methods": [ - "rename_tag_template_field_enum_value" - ] - }, - "SearchCatalog": { - "methods": [ - "search_catalog" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEntry": { - "methods": [ - "update_entry" - ] - }, - "UpdateEntryGroup": { - "methods": [ - "update_entry_group" - ] - }, - "UpdateTag": { - "methods": [ - "update_tag" - ] - }, - "UpdateTagTemplate": { - "methods": [ - "update_tag_template" - ] - }, - "UpdateTagTemplateField": { - "methods": [ - "update_tag_template_field" - ] - } - } - } - } - }, - "PolicyTagManager": { - "clients": { - "grpc": { - "libraryClient": "PolicyTagManagerClient", - "rpcs": { - "CreatePolicyTag": { - "methods": [ - "create_policy_tag" - ] - }, - "CreateTaxonomy": { - "methods": [ - "create_taxonomy" - ] - }, - "DeletePolicyTag": { - "methods": [ - "delete_policy_tag" - ] - }, - "DeleteTaxonomy": { - "methods": [ - "delete_taxonomy" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetPolicyTag": { - "methods": [ - "get_policy_tag" - ] - }, - "GetTaxonomy": { - "methods": [ - "get_taxonomy" - ] - }, - "ListPolicyTags": { - "methods": [ - "list_policy_tags" - ] - }, - "ListTaxonomies": { - "methods": [ - "list_taxonomies" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdatePolicyTag": { - "methods": [ - "update_policy_tag" - ] - }, - "UpdateTaxonomy": { - "methods": [ - "update_taxonomy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PolicyTagManagerAsyncClient", - "rpcs": { - "CreatePolicyTag": { - "methods": [ - "create_policy_tag" - ] - }, - "CreateTaxonomy": { - "methods": [ - "create_taxonomy" - ] - }, - "DeletePolicyTag": { - "methods": [ - "delete_policy_tag" - ] - }, - "DeleteTaxonomy": { - "methods": [ - "delete_taxonomy" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetPolicyTag": { - "methods": [ - "get_policy_tag" - ] - }, - "GetTaxonomy": { - "methods": [ - "get_taxonomy" - ] - }, - "ListPolicyTags": { - "methods": [ - "list_policy_tags" - ] - }, - "ListTaxonomies": { - "methods": [ - "list_taxonomies" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdatePolicyTag": { - "methods": [ - "update_policy_tag" - ] - }, - "UpdateTaxonomy": { - "methods": [ - "update_taxonomy" - ] - } - } - } - } - }, - "PolicyTagManagerSerialization": { - "clients": { - "grpc": { - "libraryClient": "PolicyTagManagerSerializationClient", - "rpcs": { - "ExportTaxonomies": { - "methods": [ - "export_taxonomies" - ] - }, - "ImportTaxonomies": { - "methods": [ - "import_taxonomies" - ] - }, - "ReplaceTaxonomy": { - "methods": [ - "replace_taxonomy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PolicyTagManagerSerializationAsyncClient", - "rpcs": { - "ExportTaxonomies": { - "methods": [ - "export_taxonomies" - ] - }, - "ImportTaxonomies": { - "methods": [ - "import_taxonomies" - ] - }, - "ReplaceTaxonomy": { - "methods": [ - "replace_taxonomy" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed b/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed deleted file mode 100644 index bb4088a3..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_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/datacatalog_v1/services/data_catalog/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__init__.py deleted file mode 100644 index b45be1eb..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/__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 DataCatalogClient -from .async_client import DataCatalogAsyncClient - -__all__ = ( - 'DataCatalogClient', - 'DataCatalogAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py deleted file mode 100644 index 1555beb7..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/async_client.py +++ /dev/null @@ -1,3009 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.services.data_catalog import pagers -from google.cloud.datacatalog_v1.types import common -from google.cloud.datacatalog_v1.types import data_source -from google.cloud.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1.types import schema -from google.cloud.datacatalog_v1.types import search -from google.cloud.datacatalog_v1.types import table_spec -from google.cloud.datacatalog_v1.types import tags -from google.cloud.datacatalog_v1.types import timestamps -from google.cloud.datacatalog_v1.types import usage -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport -from .client import DataCatalogClient - - -class DataCatalogAsyncClient: - """Data Catalog API service allows you to discover, understand, - and manage your data. - """ - - _client: DataCatalogClient - - DEFAULT_ENDPOINT = DataCatalogClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DataCatalogClient.DEFAULT_MTLS_ENDPOINT - - entry_path = staticmethod(DataCatalogClient.entry_path) - parse_entry_path = staticmethod(DataCatalogClient.parse_entry_path) - entry_group_path = staticmethod(DataCatalogClient.entry_group_path) - parse_entry_group_path = staticmethod(DataCatalogClient.parse_entry_group_path) - tag_path = staticmethod(DataCatalogClient.tag_path) - parse_tag_path = staticmethod(DataCatalogClient.parse_tag_path) - tag_template_path = staticmethod(DataCatalogClient.tag_template_path) - parse_tag_template_path = staticmethod(DataCatalogClient.parse_tag_template_path) - tag_template_field_path = staticmethod(DataCatalogClient.tag_template_field_path) - parse_tag_template_field_path = staticmethod(DataCatalogClient.parse_tag_template_field_path) - tag_template_field_enum_value_path = staticmethod(DataCatalogClient.tag_template_field_enum_value_path) - parse_tag_template_field_enum_value_path = staticmethod(DataCatalogClient.parse_tag_template_field_enum_value_path) - common_billing_account_path = staticmethod(DataCatalogClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataCatalogClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DataCatalogClient.common_folder_path) - parse_common_folder_path = staticmethod(DataCatalogClient.parse_common_folder_path) - common_organization_path = staticmethod(DataCatalogClient.common_organization_path) - parse_common_organization_path = staticmethod(DataCatalogClient.parse_common_organization_path) - common_project_path = staticmethod(DataCatalogClient.common_project_path) - parse_common_project_path = staticmethod(DataCatalogClient.parse_common_project_path) - common_location_path = staticmethod(DataCatalogClient.common_location_path) - parse_common_location_path = staticmethod(DataCatalogClient.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: - DataCatalogAsyncClient: The constructed client. - """ - return DataCatalogClient.from_service_account_info.__func__(DataCatalogAsyncClient, 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: - DataCatalogAsyncClient: The constructed client. - """ - return DataCatalogClient.from_service_account_file.__func__(DataCatalogAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DataCatalogTransport: - """Returns the transport used by the client instance. - - Returns: - DataCatalogTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DataCatalogClient).get_transport_class, type(DataCatalogClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DataCatalogTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data catalog 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, ~.DataCatalogTransport]): 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 = DataCatalogClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search_catalog(self, - request: Union[datacatalog.SearchCatalogRequest, dict] = None, - *, - scope: datacatalog.SearchCatalogRequest.Scope = None, - query: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchCatalogAsyncPager: - r"""Searches Data Catalog for multiple resources like entries and - tags that match a query. - - This is a [Custom Method] - (https://cloud.google.com/apis/design/custom_methods) that - doesn't return all information on a resource, only its ID and - high level fields. To get more information, you can subsequently - call specific get methods. - - Note: Data Catalog search queries don't guarantee full recall. - Results that match your query might not be returned, even in - subsequent result pages. Additionally, returned (and not - returned) results can vary if you repeat search queries. - - For more information, see [Data Catalog search syntax] - (https://cloud.google.com/data-catalog/docs/how-to/search-reference). - - Args: - request (Union[google.cloud.datacatalog_v1.types.SearchCatalogRequest, dict]): - The request object. Request message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - scope (:class:`google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope`): - Required. The scope of this search request. - - The ``scope`` is invalid if ``include_org_ids``, - ``include_project_ids`` are empty AND - ``include_gcp_public_datasets`` is set to ``false``. In - this case, the request returns an error. - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Optional. The query string with a minimum of 3 - characters and specific syntax. For more information, - see `Data Catalog search - syntax `__. - - An empty query string returns all data assets (in the - specified scope) that you have access to. - - A query string can be a simple ``xyz`` or qualified by - predicates: - - - ``name:x`` - - ``column:y`` - - ``description:z`` - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.services.data_catalog.pagers.SearchCatalogAsyncPager: - Response message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - 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([scope, query]) - if request is 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 = datacatalog.SearchCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_catalog, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.SearchCatalogAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_entry_group(self, - request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, - *, - parent: str = None, - entry_group_id: str = None, - entry_group: datacatalog.EntryGroup = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Creates an entry group. - - An entry group contains logically related entries together with - `Cloud Identity and Access - Management `__ policies. These - policies specify users who can create, edit, and view entries - within entry groups. - - Data Catalog automatically creates entry groups with names that - start with the ``@`` symbol for the following resources: - - - BigQuery entries (``@bigquery``) - - Pub/Sub topics (``@pubsub``) - - Dataproc Metastore services - (``@dataproc_metastore_{SERVICE_NAME_HASH}``) - - You can create your own entry groups for Cloud Storage fileset - entries and custom entries together with the corresponding IAM - policies. User-created entry groups can't contain the ``@`` - symbol, it is reserved for automatically created groups. - - Entry groups, like entries, can be searched. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateEntryGroupRequest, dict]): - The request object. Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. - parent (:class:`str`): - Required. The names of the project - and location that the new entry group - belongs to. Note: The entry group - itself and its child resources might not - be stored in the location specified in - its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group_id (:class:`str`): - Required. The ID of the entry group to create. - - The ID must contain only letters (a-z, A-Z), numbers - (0-9), underscores (_), and must start with a letter or - underscore. The maximum size is 64 bytes when encoded in - UTF-8. - - This corresponds to the ``entry_group_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group (:class:`google.cloud.datacatalog_v1.types.EntryGroup`): - The entry group to create. Defaults - to empty. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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, entry_group_id, entry_group]) - if request is 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 = datacatalog.CreateEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_group_id is not None: - request.entry_group_id = entry_group_id - if entry_group is not None: - request.entry_group = entry_group - - # 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_entry_group, - default_timeout=None, - client_info=DEFAULT_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_entry_group(self, - request: Union[datacatalog.GetEntryGroupRequest, dict] = None, - *, - name: str = None, - read_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Gets an entry group. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetEntryGroupRequest, dict]): - The request object. Request message for - [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. - name (:class:`str`): - Required. The name of the entry group - to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - read_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to return. If empty or - omitted, all fields are returned. - - This corresponds to the ``read_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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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, read_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 = datacatalog.GetEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if read_mask is not None: - request.read_mask = read_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.get_entry_group, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_entry_group(self, - request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, - *, - entry_group: datacatalog.EntryGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Updates an entry group. - - You must enable the Data Catalog API in the project identified - by the ``entry_group.name`` parameter. For more information, see - `Data Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateEntryGroupRequest, dict]): - The request object. Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. - entry_group (:class:`google.cloud.datacatalog_v1.types.EntryGroup`): - Required. Updates for the entry group. The ``name`` - field must be set. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Names of fields whose values to - overwrite on an entry group. - If this parameter is absent or empty, - all modifiable fields are overwritten. - If such fields are non-required and - omitted in the request body, their - values are emptied. - - 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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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([entry_group, 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 = datacatalog.UpdateEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry_group is not None: - request.entry_group = entry_group - 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_entry_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry_group.name", request.entry_group.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entry_group(self, - request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an entry group. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteEntryGroupRequest, dict]): - The request object. Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. - name (:class:`str`): - Required. The name of the entry group - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = datacatalog.DeleteEntryGroupRequest(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_entry_group, - default_timeout=None, - client_info=DEFAULT_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_entry_groups(self, - request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntryGroupsAsyncPager: - r"""Lists entry groups. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListEntryGroupsRequest, dict]): - The request object. Request message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - parent (:class:`str`): - Required. The name of the location - that contains the entry groups to list. - Can be provided as a URL. - - 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.datacatalog_v1.services.data_catalog.pagers.ListEntryGroupsAsyncPager: - Response message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - - 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 = datacatalog.ListEntryGroupsRequest(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_entry_groups, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEntryGroupsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_entry(self, - request: Union[datacatalog.CreateEntryRequest, dict] = None, - *, - parent: str = None, - entry_id: str = None, - entry: datacatalog.Entry = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Creates an entry. - - You can create entries only with 'FILESET', 'CLUSTER', - 'DATA_STREAM', or custom types. Data Catalog automatically - creates entries with other types during metadata ingestion from - integrated systems. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - An entry group can have a maximum of 100,000 entries. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateEntryRequest, dict]): - The request object. Request message for - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. - parent (:class:`str`): - Required. The name of the entry group - this entry belongs to. - Note: The entry itself and its child - resources might not be stored in the - location specified in its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_id (:class:`str`): - Required. The ID of the entry to create. - - The ID must contain only letters (a-z, A-Z), numbers - (0-9), and underscores (_). The maximum size is 64 bytes - when encoded in UTF-8. - - This corresponds to the ``entry_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry (:class:`google.cloud.datacatalog_v1.types.Entry`): - Required. The entry to create. - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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, entry_id, entry]) - if request is 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 = datacatalog.CreateEntryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_id is not None: - request.entry_id = entry_id - if entry is not None: - request.entry = entry - - # 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_entry, - default_timeout=None, - client_info=DEFAULT_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_entry(self, - request: Union[datacatalog.UpdateEntryRequest, dict] = None, - *, - entry: datacatalog.Entry = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Updates an existing entry. - - You must enable the Data Catalog API in the project identified - by the ``entry.name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateEntryRequest, dict]): - The request object. Request message for - [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. - entry (:class:`google.cloud.datacatalog_v1.types.Entry`): - Required. Updates for the entry. The ``name`` field must - be set. - - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Names of fields whose values to overwrite on an entry. - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied. - - You can modify only the fields listed below. - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - For entries with type ``FILESET``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - For entries with ``user_specified_type``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``user_specified_type`` - - ``user_specified_system`` - - ``linked_resource`` - - ``source_system_timestamps`` - - 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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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([entry, 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 = datacatalog.UpdateEntryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry is not None: - request.entry = entry - 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_entry, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry.name", request.entry.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entry(self, - request: Union[datacatalog.DeleteEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing entry. - - You can delete only the entries created by the - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] - method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteEntryRequest, dict]): - The request object. Request message for - [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. - name (:class:`str`): - Required. The name of the entry to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = datacatalog.DeleteEntryRequest(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_entry, - default_timeout=None, - client_info=DEFAULT_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_entry(self, - request: Union[datacatalog.GetEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetEntryRequest, dict]): - The request object. Request message for - [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. - name (:class:`str`): - Required. The name of the entry to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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 = datacatalog.GetEntryRequest(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_entry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def lookup_entry(self, - request: Union[datacatalog.LookupEntryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry by its target resource name. - The resource name comes from the source Google Cloud - Platform service. - - Args: - request (Union[google.cloud.datacatalog_v1.types.LookupEntryRequest, dict]): - The request object. Request message for - [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # Create or coerce a protobuf request object. - request = datacatalog.LookupEntryRequest(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.lookup_entry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_entries(self, - request: Union[datacatalog.ListEntriesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntriesAsyncPager: - r"""Lists entries. - - Note: Currently, this method can list only custom entries. To - get a list of both custom and automatically created entries, use - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): - The request object. Request message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - parent (:class:`str`): - Required. The name of the entry group - that contains the entries to list. - Can be provided in URL format. - - 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.datacatalog_v1.services.data_catalog.pagers.ListEntriesAsyncPager: - Response message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - - 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 = datacatalog.ListEntriesRequest(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_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEntriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_tag_template(self, - request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, - *, - parent: str = None, - tag_template_id: str = None, - tag_template: tags.TagTemplate = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Creates a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateRequest, dict]): - The request object. Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. - parent (:class:`str`): - Required. The name of the project and the template - location - `region `__. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_id (:class:`str`): - Required. The ID of the tag template to create. - - The ID must contain only lowercase letters (a-z), - numbers (0-9), or underscores (_), and must start with a - letter or underscore. The maximum size is 64 bytes when - encoded in UTF-8. - - This corresponds to the ``tag_template_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template (:class:`google.cloud.datacatalog_v1.types.TagTemplate`): - Required. The tag template to create. - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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, tag_template_id, tag_template]) - if request is 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 = datacatalog.CreateTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_id is not None: - request.tag_template_id = tag_template_id - if tag_template is not None: - request.tag_template = tag_template - - # 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_tag_template, - default_timeout=None, - client_info=DEFAULT_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_tag_template(self, - request: Union[datacatalog.GetTagTemplateRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Gets a tag template. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetTagTemplateRequest, dict]): - The request object. Request message for - [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. - name (:class:`str`): - Required. The name of the tag - template to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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 = datacatalog.GetTagTemplateRequest(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_tag_template, - default_timeout=None, - client_info=DEFAULT_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 update_tag_template(self, - request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, - *, - tag_template: tags.TagTemplate = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Updates a tag template. - - You can't update template fields with this method. These fields - are separate resources with their own create, update, and delete - methods. - - You must enable the Data Catalog API in the project identified - by the ``tag_template.name`` parameter. For more information, - see `Data Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateRequest, dict]): - The request object. Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. - tag_template (:class:`google.cloud.datacatalog_v1.types.TagTemplate`): - Required. The template to update. The ``name`` field - must be set. - - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Names of fields whose values to overwrite on a tag - template. Currently, only ``display_name`` and - ``is_publicly_readable`` can be overwritten. - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied. - - Note: Updating the ``is_publicly_readable`` field may - require up to 12 hours to take effect in search results. - Additionally, it also requires the - ``tagTemplates.getIamPolicy`` and - ``tagTemplates.setIamPolicy`` permissions. - - 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.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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([tag_template, 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 = datacatalog.UpdateTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_template is not None: - request.tag_template = tag_template - 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_tag_template, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_template.name", request.tag_template.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_tag_template(self, - request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag template and all tags that use it. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateRequest, dict]): - The request object. Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. - name (:class:`str`): - Required. The name of the tag - template to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (:class:`bool`): - Required. If true, deletes all tags that use this - template. - - Currently, ``true`` is the only supported value. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 = datacatalog.DeleteTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # 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_tag_template, - default_timeout=None, - client_info=DEFAULT_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 create_tag_template_field(self, - request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, - *, - parent: str = None, - tag_template_field_id: str = None, - tag_template_field: tags.TagTemplateField = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Creates a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateFieldRequest, dict]): - The request object. Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. - parent (:class:`str`): - Required. The name of the project and the template - location - `region `__. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field_id (:class:`str`): - Required. The ID of the tag template field to create. - - Note: Adding a required field to an existing template is - *not* allowed. - - Field IDs can contain letters (both uppercase and - lowercase), numbers (0-9), underscores (_) and dashes - (-). Field IDs must be at least 1 character long and at - most 128 characters long. Field IDs must also be unique - within their template. - - This corresponds to the ``tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (:class:`google.cloud.datacatalog_v1.types.TagTemplateField`): - Required. The tag template field to - create. - - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field_id, tag_template_field]) - if request is 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 = datacatalog.CreateTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_field_id is not None: - request.tag_template_field_id = tag_template_field_id - if tag_template_field is not None: - request.tag_template_field = tag_template_field - - # 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_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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_tag_template_field(self, - request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - tag_template_field: tags.TagTemplateField = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Updates a field in a tag template. - - You can't update the field type with this method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateFieldRequest, dict]): - The request object. Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. - name (:class:`str`): - Required. The name of the tag - template field. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (:class:`google.cloud.datacatalog_v1.types.TagTemplateField`): - Required. The template to update. - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Names of fields whose values to overwrite on - an individual field of a tag template. The following - fields are modifiable: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied with one exception: when updating an enum type, - the provided values are merged with the existing values. - Therefore, enum values can only be added, existing enum - values cannot be deleted or renamed. - - Additionally, updating a template field from optional to - required is *not* allowed. - - 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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field, 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 = datacatalog.UpdateTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if tag_template_field is not None: - request.tag_template_field = tag_template_field - 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_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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 rename_tag_template_field(self, - request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - new_tag_template_field_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Args: - request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldRequest, dict]): - The request object. Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. - name (:class:`str`): - Required. The name of the tag - template field. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_tag_template_field_id (:class:`str`): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - - This corresponds to the ``new_tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_tag_template_field_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datacatalog.RenameTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_tag_template_field_id is not None: - request.new_tag_template_field_id = new_tag_template_field_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.rename_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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 rename_tag_template_field_enum_value(self, - request: Union[datacatalog.RenameTagTemplateFieldEnumValueRequest, dict] = None, - *, - name: str = None, - new_enum_value_display_name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames an enum value in a tag template. - Within a single enum field, enum values must be unique. - - Args: - request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldEnumValueRequest, dict]): - The request object. Request message for - [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. - name (:class:`str`): - Required. The name of the enum field - value. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_enum_value_display_name (:class:`str`): - Required. The new display name of the enum value. For - example, ``my_new_enum_value``. - - This corresponds to the ``new_enum_value_display_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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_enum_value_display_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 = datacatalog.RenameTagTemplateFieldEnumValueRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_enum_value_display_name is not None: - request.new_enum_value_display_name = new_enum_value_display_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.rename_tag_template_field_enum_value, - default_timeout=None, - client_info=DEFAULT_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_tag_template_field(self, - request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a field in a tag template and all uses of this field - from the tags based on this template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateFieldRequest, dict]): - The request object. Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. - name (:class:`str`): - Required. The name of the tag - template field to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (:class:`bool`): - Required. If true, deletes this field from any tags that - use it. - - Currently, ``true`` is the only supported value. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 = datacatalog.DeleteTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # 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_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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 create_tag(self, - request: Union[datacatalog.CreateTagRequest, dict] = None, - *, - parent: str = None, - tag: tags.Tag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Creates a tag and assigns it to: - - - An [Entry][google.cloud.datacatalog.v1.Entry] if the method - name is - ``projects.locations.entryGroups.entries.tags.create``. - - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the - method name is - ``projects.locations.entryGroups.tags.create``. - - Note: The project identified by the ``parent`` parameter for the - [tag] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) - and the [tag template] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) - used to create the tag must be in the same organization. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagRequest, dict]): - The request object. Request message for - [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. - parent (:class:`str`): - Required. The name of the resource to - attach this tag to. - Tags can be attached to entries or entry - groups. An entry can have up to 1000 - attached tags. - - Note: The tag and its child resources - might not be stored in the location - specified in its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag (:class:`google.cloud.datacatalog_v1.types.Tag`): - Required. The tag to create. - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Tag: - Tags contain custom metadata and are attached to Data Catalog resources. Tags - conform with the specification of their tag template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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, tag]) - if request is 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 = datacatalog.CreateTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag is not None: - request.tag = tag - - # 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_tag, - default_timeout=None, - client_info=DEFAULT_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_tag(self, - request: Union[datacatalog.UpdateTagRequest, dict] = None, - *, - tag: tags.Tag = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Updates an existing tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagRequest, dict]): - The request object. Request message for - [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. - tag (:class:`google.cloud.datacatalog_v1.types.Tag`): - Required. The updated tag. The "name" - field must be set. - - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Names of fields whose values to overwrite on a tag. - Currently, a tag has the only modifiable field with the - name ``fields``. - - In general, if this parameter is absent or empty, all - modifiable fields are overwritten. If such fields are - non-required and omitted in the request body, their - values are emptied. - - 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.datacatalog_v1.types.Tag: - Tags contain custom metadata and are attached to Data Catalog resources. Tags - conform with the specification of their tag template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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([tag, 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 = datacatalog.UpdateTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag is not None: - request.tag = tag - 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_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag.name", request.tag.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_tag(self, - request: Union[datacatalog.DeleteTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagRequest, dict]): - The request object. Request message for - [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. - name (:class:`str`): - Required. The name of the tag to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = datacatalog.DeleteTagRequest(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_tag, - default_timeout=None, - client_info=DEFAULT_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_tags(self, - request: Union[datacatalog.ListTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTagsAsyncPager: - r"""Lists tags assigned to an - [Entry][google.cloud.datacatalog.v1.Entry]. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListTagsRequest, dict]): - The request object. Request message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - parent (:class:`str`): - Required. The name of the Data Catalog resource to list - the tags of. - - The resource can be an - [Entry][google.cloud.datacatalog.v1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] - (without ``/entries/{entries}`` at the end). - - 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.datacatalog_v1.services.data_catalog.pagers.ListTagsAsyncPager: - Response message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - - 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 = datacatalog.ListTagsRequest(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_tags, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTagsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets an access control policy for a resource. Replaces any - existing policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method sets policies only within Data Catalog and - can't be used to manage policies in BigQuery, Pub/Sub, Dataproc - Metastore, and any external Google Cloud Platform resources - synced with the Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. - - May return: - - - A\ ``NOT_FOUND`` error if the resource doesn't exist or you - don't have the permission to view it. - - An empty policy if the resource exists but doesn't have a set - policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method doesn't get policies from Google Cloud - Platform resources ingested into Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # 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_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Gets your permissions on a resource. - Returns an empty set of permissions if the resource - doesn't exist. - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method gets policies only within Data Catalog - and can't be used to get policies from BigQuery, - Pub/Sub, Dataproc Metastore, and any external Google - Cloud Platform resources ingested into Data Catalog. - No Google IAM permissions are required to call this - method. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataCatalogAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py deleted file mode 100644 index 25b6af01..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/client.py +++ /dev/null @@ -1,3201 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.services.data_catalog import pagers -from google.cloud.datacatalog_v1.types import common -from google.cloud.datacatalog_v1.types import data_source -from google.cloud.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1.types import schema -from google.cloud.datacatalog_v1.types import search -from google.cloud.datacatalog_v1.types import table_spec -from google.cloud.datacatalog_v1.types import tags -from google.cloud.datacatalog_v1.types import timestamps -from google.cloud.datacatalog_v1.types import usage -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DataCatalogGrpcTransport -from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport - - -class DataCatalogClientMeta(type): - """Metaclass for the DataCatalog 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[DataCatalogTransport]] - _transport_registry["grpc"] = DataCatalogGrpcTransport - _transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DataCatalogTransport]: - """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 DataCatalogClient(metaclass=DataCatalogClientMeta): - """Data Catalog API service allows you to discover, understand, - and manage your data. - """ - - @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 = "datacatalog.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: - DataCatalogClient: 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: - DataCatalogClient: 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) -> DataCatalogTransport: - """Returns the transport used by the client instance. - - Returns: - DataCatalogTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entry_path(project: str,location: str,entry_group: str,entry: str,) -> str: - """Returns a fully-qualified entry string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) - - @staticmethod - def parse_entry_path(path: str) -> Dict[str,str]: - """Parses a entry path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def entry_group_path(project: str,location: str,entry_group: str,) -> str: - """Returns a fully-qualified entry_group string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) - - @staticmethod - def parse_entry_group_path(path: str) -> Dict[str,str]: - """Parses a entry_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_path(project: str,location: str,entry_group: str,entry: str,tag: str,) -> str: - """Returns a fully-qualified tag string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) - - @staticmethod - def parse_tag_path(path: str) -> Dict[str,str]: - """Parses a tag path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)/tags/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_template_path(project: str,location: str,tag_template: str,) -> str: - """Returns a fully-qualified tag_template string.""" - return "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) - - @staticmethod - def parse_tag_template_path(path: str) -> Dict[str,str]: - """Parses a tag_template path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_template_field_path(project: str,location: str,tag_template: str,field: str,) -> str: - """Returns a fully-qualified tag_template_field string.""" - return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) - - @staticmethod - def parse_tag_template_field_path(path: str) -> Dict[str,str]: - """Parses a tag_template_field path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_template_field_enum_value_path(project: str,location: str,tag_template: str,tag_template_field_id: str,enum_value_display_name: str,) -> str: - """Returns a fully-qualified tag_template_field_enum_value string.""" - return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{tag_template_field_id}/enumValues/{enum_value_display_name}".format(project=project, location=location, tag_template=tag_template, tag_template_field_id=tag_template_field_id, enum_value_display_name=enum_value_display_name, ) - - @staticmethod - def parse_tag_template_field_enum_value_path(path: str) -> Dict[str,str]: - """Parses a tag_template_field_enum_value path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?P.+?)/enumValues/(?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, DataCatalogTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data catalog 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, DataCatalogTransport]): 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, DataCatalogTransport): - # transport is a DataCatalogTransport 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=True, - ) - - def search_catalog(self, - request: Union[datacatalog.SearchCatalogRequest, dict] = None, - *, - scope: datacatalog.SearchCatalogRequest.Scope = None, - query: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchCatalogPager: - r"""Searches Data Catalog for multiple resources like entries and - tags that match a query. - - This is a [Custom Method] - (https://cloud.google.com/apis/design/custom_methods) that - doesn't return all information on a resource, only its ID and - high level fields. To get more information, you can subsequently - call specific get methods. - - Note: Data Catalog search queries don't guarantee full recall. - Results that match your query might not be returned, even in - subsequent result pages. Additionally, returned (and not - returned) results can vary if you repeat search queries. - - For more information, see [Data Catalog search syntax] - (https://cloud.google.com/data-catalog/docs/how-to/search-reference). - - Args: - request (Union[google.cloud.datacatalog_v1.types.SearchCatalogRequest, dict]): - The request object. Request message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - scope (google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope): - Required. The scope of this search request. - - The ``scope`` is invalid if ``include_org_ids``, - ``include_project_ids`` are empty AND - ``include_gcp_public_datasets`` is set to ``false``. In - this case, the request returns an error. - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Optional. The query string with a minimum of 3 - characters and specific syntax. For more information, - see `Data Catalog search - syntax `__. - - An empty query string returns all data assets (in the - specified scope) that you have access to. - - A query string can be a simple ``xyz`` or qualified by - predicates: - - - ``name:x`` - - ``column:y`` - - ``description:z`` - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.services.data_catalog.pagers.SearchCatalogPager: - Response message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - 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([scope, query]) - if request is 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 datacatalog.SearchCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.SearchCatalogRequest): - request = datacatalog.SearchCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_catalog] - - # 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.SearchCatalogPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_entry_group(self, - request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, - *, - parent: str = None, - entry_group_id: str = None, - entry_group: datacatalog.EntryGroup = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Creates an entry group. - - An entry group contains logically related entries together with - `Cloud Identity and Access - Management `__ policies. These - policies specify users who can create, edit, and view entries - within entry groups. - - Data Catalog automatically creates entry groups with names that - start with the ``@`` symbol for the following resources: - - - BigQuery entries (``@bigquery``) - - Pub/Sub topics (``@pubsub``) - - Dataproc Metastore services - (``@dataproc_metastore_{SERVICE_NAME_HASH}``) - - You can create your own entry groups for Cloud Storage fileset - entries and custom entries together with the corresponding IAM - policies. User-created entry groups can't contain the ``@`` - symbol, it is reserved for automatically created groups. - - Entry groups, like entries, can be searched. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateEntryGroupRequest, dict]): - The request object. Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. - parent (str): - Required. The names of the project - and location that the new entry group - belongs to. Note: The entry group - itself and its child resources might not - be stored in the location specified in - its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group_id (str): - Required. The ID of the entry group to create. - - The ID must contain only letters (a-z, A-Z), numbers - (0-9), underscores (_), and must start with a letter or - underscore. The maximum size is 64 bytes when encoded in - UTF-8. - - This corresponds to the ``entry_group_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group (google.cloud.datacatalog_v1.types.EntryGroup): - The entry group to create. Defaults - to empty. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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, entry_group_id, entry_group]) - if request is 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 datacatalog.CreateEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateEntryGroupRequest): - request = datacatalog.CreateEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_group_id is not None: - request.entry_group_id = entry_group_id - if entry_group is not None: - request.entry_group = entry_group - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entry_group] - - # 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_entry_group(self, - request: Union[datacatalog.GetEntryGroupRequest, dict] = None, - *, - name: str = None, - read_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Gets an entry group. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetEntryGroupRequest, dict]): - The request object. Request message for - [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. - name (str): - Required. The name of the entry group - to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return. If empty or - omitted, all fields are returned. - - This corresponds to the ``read_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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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, read_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 datacatalog.GetEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetEntryGroupRequest): - request = datacatalog.GetEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if read_mask is not None: - request.read_mask = read_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_entry_group] - - # Certain fields should be 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 update_entry_group(self, - request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, - *, - entry_group: datacatalog.EntryGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Updates an entry group. - - You must enable the Data Catalog API in the project identified - by the ``entry_group.name`` parameter. For more information, see - `Data Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateEntryGroupRequest, dict]): - The request object. Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. - entry_group (google.cloud.datacatalog_v1.types.EntryGroup): - Required. Updates for the entry group. The ``name`` - field must be set. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to - overwrite on an entry group. - If this parameter is absent or empty, - all modifiable fields are overwritten. - If such fields are non-required and - omitted in the request body, their - values are emptied. - - 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.datacatalog_v1.types.EntryGroup: - Entry group metadata. - - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1.Entry] resources. - - """ - # 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([entry_group, 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 datacatalog.UpdateEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateEntryGroupRequest): - request = datacatalog.UpdateEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry_group is not None: - request.entry_group = entry_group - 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_entry_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry_group.name", request.entry_group.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_entry_group(self, - request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an entry group. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteEntryGroupRequest, dict]): - The request object. Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. - name (str): - Required. The name of the entry group - to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 datacatalog.DeleteEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteEntryGroupRequest): - request = datacatalog.DeleteEntryGroupRequest(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_entry_group] - - # Certain fields should be 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_entry_groups(self, - request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntryGroupsPager: - r"""Lists entry groups. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListEntryGroupsRequest, dict]): - The request object. Request message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - parent (str): - Required. The name of the location - that contains the entry groups to list. - Can be provided as a URL. - - 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.datacatalog_v1.services.data_catalog.pagers.ListEntryGroupsPager: - Response message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - - 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 datacatalog.ListEntryGroupsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListEntryGroupsRequest): - request = datacatalog.ListEntryGroupsRequest(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_entry_groups] - - # 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.ListEntryGroupsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_entry(self, - request: Union[datacatalog.CreateEntryRequest, dict] = None, - *, - parent: str = None, - entry_id: str = None, - entry: datacatalog.Entry = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Creates an entry. - - You can create entries only with 'FILESET', 'CLUSTER', - 'DATA_STREAM', or custom types. Data Catalog automatically - creates entries with other types during metadata ingestion from - integrated systems. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - An entry group can have a maximum of 100,000 entries. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateEntryRequest, dict]): - The request object. Request message for - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. - parent (str): - Required. The name of the entry group - this entry belongs to. - Note: The entry itself and its child - resources might not be stored in the - location specified in its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_id (str): - Required. The ID of the entry to create. - - The ID must contain only letters (a-z, A-Z), numbers - (0-9), and underscores (_). The maximum size is 64 bytes - when encoded in UTF-8. - - This corresponds to the ``entry_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry (google.cloud.datacatalog_v1.types.Entry): - Required. The entry to create. - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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, entry_id, entry]) - if request is 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 datacatalog.CreateEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateEntryRequest): - request = datacatalog.CreateEntryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_id is not None: - request.entry_id = entry_id - if entry is not None: - request.entry = entry - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entry] - - # 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_entry(self, - request: Union[datacatalog.UpdateEntryRequest, dict] = None, - *, - entry: datacatalog.Entry = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Updates an existing entry. - - You must enable the Data Catalog API in the project identified - by the ``entry.name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateEntryRequest, dict]): - The request object. Request message for - [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. - entry (google.cloud.datacatalog_v1.types.Entry): - Required. Updates for the entry. The ``name`` field must - be set. - - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on an entry. - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied. - - You can modify only the fields listed below. - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - For entries with type ``FILESET``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - For entries with ``user_specified_type``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``user_specified_type`` - - ``user_specified_system`` - - ``linked_resource`` - - ``source_system_timestamps`` - - 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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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([entry, 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 datacatalog.UpdateEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateEntryRequest): - request = datacatalog.UpdateEntryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry is not None: - request.entry = entry - 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_entry] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry.name", request.entry.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_entry(self, - request: Union[datacatalog.DeleteEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing entry. - - You can delete only the entries created by the - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] - method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteEntryRequest, dict]): - The request object. Request message for - [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. - name (str): - Required. The name of the entry to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 datacatalog.DeleteEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteEntryRequest): - request = datacatalog.DeleteEntryRequest(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_entry] - - # Certain fields should be 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_entry(self, - request: Union[datacatalog.GetEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetEntryRequest, dict]): - The request object. Request message for - [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. - name (str): - Required. The name of the entry to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # 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 datacatalog.GetEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetEntryRequest): - request = datacatalog.GetEntryRequest(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_entry] - - # Certain fields should be 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 lookup_entry(self, - request: Union[datacatalog.LookupEntryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry by its target resource name. - The resource name comes from the source Google Cloud - Platform service. - - Args: - request (Union[google.cloud.datacatalog_v1.types.LookupEntryRequest, dict]): - The request object. Request message for - [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Entry: - Entry metadata. - A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or - a Pub/Sub topic) or outside of it. You can use the - linked_resource field in the entry resource to refer - to the original resource ID of the source system. - - An entry resource contains resource details, for - example, its schema. Additionally, you can attach - flexible metadata to an entry in the form of a - [Tag][google.cloud.datacatalog.v1.Tag]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a datacatalog.LookupEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.LookupEntryRequest): - request = datacatalog.LookupEntryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.lookup_entry] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_entries(self, - request: Union[datacatalog.ListEntriesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntriesPager: - r"""Lists entries. - - Note: Currently, this method can list only custom entries. To - get a list of both custom and automatically created entries, use - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListEntriesRequest, dict]): - The request object. Request message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - parent (str): - Required. The name of the entry group - that contains the entries to list. - Can be provided in URL format. - - 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.datacatalog_v1.services.data_catalog.pagers.ListEntriesPager: - Response message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - - 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 datacatalog.ListEntriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListEntriesRequest): - request = datacatalog.ListEntriesRequest(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_entries] - - # 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.ListEntriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_tag_template(self, - request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, - *, - parent: str = None, - tag_template_id: str = None, - tag_template: tags.TagTemplate = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Creates a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateRequest, dict]): - The request object. Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. - parent (str): - Required. The name of the project and the template - location - `region `__. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_id (str): - Required. The ID of the tag template to create. - - The ID must contain only lowercase letters (a-z), - numbers (0-9), or underscores (_), and must start with a - letter or underscore. The maximum size is 64 bytes when - encoded in UTF-8. - - This corresponds to the ``tag_template_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template (google.cloud.datacatalog_v1.types.TagTemplate): - Required. The tag template to create. - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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, tag_template_id, tag_template]) - if request is 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 datacatalog.CreateTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagTemplateRequest): - request = datacatalog.CreateTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_id is not None: - request.tag_template_id = tag_template_id - if tag_template is not None: - request.tag_template = tag_template - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_template] - - # 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_tag_template(self, - request: Union[datacatalog.GetTagTemplateRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Gets a tag template. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetTagTemplateRequest, dict]): - The request object. Request message for - [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. - name (str): - Required. The name of the tag - template to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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 datacatalog.GetTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetTagTemplateRequest): - request = datacatalog.GetTagTemplateRequest(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_tag_template] - - # Certain fields should be 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 update_tag_template(self, - request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, - *, - tag_template: tags.TagTemplate = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Updates a tag template. - - You can't update template fields with this method. These fields - are separate resources with their own create, update, and delete - methods. - - You must enable the Data Catalog API in the project identified - by the ``tag_template.name`` parameter. For more information, - see `Data Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateRequest, dict]): - The request object. Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. - tag_template (google.cloud.datacatalog_v1.types.TagTemplate): - Required. The template to update. The ``name`` field - must be set. - - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on a tag - template. Currently, only ``display_name`` and - ``is_publicly_readable`` can be overwritten. - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied. - - Note: Updating the ``is_publicly_readable`` field may - require up to 12 hours to take effect in search results. - Additionally, it also requires the - ``tagTemplates.getIamPolicy`` and - ``tagTemplates.setIamPolicy`` permissions. - - 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.datacatalog_v1.types.TagTemplate: - A tag template defines a tag that can have one or more - typed fields. - - The template is used to create tags that are attached - to GCP resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. For example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag - template to tag resources. - - """ - # 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([tag_template, 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 datacatalog.UpdateTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagTemplateRequest): - request = datacatalog.UpdateTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_template is not None: - request.tag_template = tag_template - 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_tag_template] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_template.name", request.tag_template.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_tag_template(self, - request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag template and all tags that use it. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateRequest, dict]): - The request object. Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. - name (str): - Required. The name of the tag - template to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (bool): - Required. If true, deletes all tags that use this - template. - - Currently, ``true`` is the only supported value. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 datacatalog.DeleteTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagTemplateRequest): - request = datacatalog.DeleteTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_template] - - # Certain fields should be 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 create_tag_template_field(self, - request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, - *, - parent: str = None, - tag_template_field_id: str = None, - tag_template_field: tags.TagTemplateField = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Creates a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagTemplateFieldRequest, dict]): - The request object. Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. - parent (str): - Required. The name of the project and the template - location - `region `__. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field_id (str): - Required. The ID of the tag template field to create. - - Note: Adding a required field to an existing template is - *not* allowed. - - Field IDs can contain letters (both uppercase and - lowercase), numbers (0-9), underscores (_) and dashes - (-). Field IDs must be at least 1 character long and at - most 128 characters long. Field IDs must also be unique - within their template. - - This corresponds to the ``tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): - Required. The tag template field to - create. - - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field_id, tag_template_field]) - if request is 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 datacatalog.CreateTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagTemplateFieldRequest): - request = datacatalog.CreateTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_field_id is not None: - request.tag_template_field_id = tag_template_field_id - if tag_template_field is not None: - request.tag_template_field = tag_template_field - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_template_field] - - # 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_tag_template_field(self, - request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - tag_template_field: tags.TagTemplateField = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Updates a field in a tag template. - - You can't update the field type with this method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagTemplateFieldRequest, dict]): - The request object. Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. - name (str): - Required. The name of the tag - template field. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): - Required. The template to update. - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Names of fields whose values to overwrite on - an individual field of a tag template. The following - fields are modifiable: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If this parameter is absent or empty, all modifiable - fields are overwritten. If such fields are non-required - and omitted in the request body, their values are - emptied with one exception: when updating an enum type, - the provided values are merged with the existing values. - Therefore, enum values can only be added, existing enum - values cannot be deleted or renamed. - - Additionally, updating a template field from optional to - required is *not* allowed. - - 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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field, 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 datacatalog.UpdateTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagTemplateFieldRequest): - request = datacatalog.UpdateTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if tag_template_field is not None: - request.tag_template_field = tag_template_field - 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_tag_template_field] - - # Certain fields should be 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 rename_tag_template_field(self, - request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - new_tag_template_field_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Args: - request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldRequest, dict]): - The request object. Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. - name (str): - Required. The name of the tag - template field. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_tag_template_field_id (str): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - - This corresponds to the ``new_tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_tag_template_field_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datacatalog.RenameTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.RenameTagTemplateFieldRequest): - request = datacatalog.RenameTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_tag_template_field_id is not None: - request.new_tag_template_field_id = new_tag_template_field_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field] - - # Certain fields should be 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 rename_tag_template_field_enum_value(self, - request: Union[datacatalog.RenameTagTemplateFieldEnumValueRequest, dict] = None, - *, - name: str = None, - new_enum_value_display_name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames an enum value in a tag template. - Within a single enum field, enum values must be unique. - - Args: - request (Union[google.cloud.datacatalog_v1.types.RenameTagTemplateFieldEnumValueRequest, dict]): - The request object. Request message for - [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. - name (str): - Required. The name of the enum field - value. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_enum_value_display_name (str): - Required. The new display name of the enum value. For - example, ``my_new_enum_value``. - - This corresponds to the ``new_enum_value_display_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.datacatalog_v1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_enum_value_display_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 datacatalog.RenameTagTemplateFieldEnumValueRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.RenameTagTemplateFieldEnumValueRequest): - request = datacatalog.RenameTagTemplateFieldEnumValueRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_enum_value_display_name is not None: - request.new_enum_value_display_name = new_enum_value_display_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field_enum_value] - - # Certain fields should be 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_tag_template_field(self, - request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a field in a tag template and all uses of this field - from the tags based on this template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagTemplateFieldRequest, dict]): - The request object. Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. - name (str): - Required. The name of the tag - template field to delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (bool): - Required. If true, deletes this field from any tags that - use it. - - Currently, ``true`` is the only supported value. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 datacatalog.DeleteTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagTemplateFieldRequest): - request = datacatalog.DeleteTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_template_field] - - # Certain fields should be 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 create_tag(self, - request: Union[datacatalog.CreateTagRequest, dict] = None, - *, - parent: str = None, - tag: tags.Tag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Creates a tag and assigns it to: - - - An [Entry][google.cloud.datacatalog.v1.Entry] if the method - name is - ``projects.locations.entryGroups.entries.tags.create``. - - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the - method name is - ``projects.locations.entryGroups.tags.create``. - - Note: The project identified by the ``parent`` parameter for the - [tag] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) - and the [tag template] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) - used to create the tag must be in the same organization. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTagRequest, dict]): - The request object. Request message for - [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. - parent (str): - Required. The name of the resource to - attach this tag to. - Tags can be attached to entries or entry - groups. An entry can have up to 1000 - attached tags. - - Note: The tag and its child resources - might not be stored in the location - specified in its name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag (google.cloud.datacatalog_v1.types.Tag): - Required. The tag to create. - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Tag: - Tags contain custom metadata and are attached to Data Catalog resources. Tags - conform with the specification of their tag template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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, tag]) - if request is 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 datacatalog.CreateTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagRequest): - request = datacatalog.CreateTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag is not None: - request.tag = tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag] - - # 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_tag(self, - request: Union[datacatalog.UpdateTagRequest, dict] = None, - *, - tag: tags.Tag = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Updates an existing tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTagRequest, dict]): - The request object. Request message for - [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. - tag (google.cloud.datacatalog_v1.types.Tag): - Required. The updated tag. The "name" - field must be set. - - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on a tag. - Currently, a tag has the only modifiable field with the - name ``fields``. - - In general, if this parameter is absent or empty, all - modifiable fields are overwritten. If such fields are - non-required and omitted in the request body, their - values are emptied. - - 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.datacatalog_v1.types.Tag: - Tags contain custom metadata and are attached to Data Catalog resources. Tags - conform with the specification of their tag template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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([tag, 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 datacatalog.UpdateTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagRequest): - request = datacatalog.UpdateTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag is not None: - request.tag = tag - 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_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag.name", request.tag.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_tag(self, - request: Union[datacatalog.DeleteTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTagRequest, dict]): - The request object. Request message for - [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. - name (str): - Required. The name of the tag to - delete. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 datacatalog.DeleteTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagRequest): - request = datacatalog.DeleteTagRequest(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_tag] - - # Certain fields should be 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_tags(self, - request: Union[datacatalog.ListTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTagsPager: - r"""Lists tags assigned to an - [Entry][google.cloud.datacatalog.v1.Entry]. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListTagsRequest, dict]): - The request object. Request message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - parent (str): - Required. The name of the Data Catalog resource to list - the tags of. - - The resource can be an - [Entry][google.cloud.datacatalog.v1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] - (without ``/entries/{entries}`` at the end). - - 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.datacatalog_v1.services.data_catalog.pagers.ListTagsPager: - Response message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - - 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 datacatalog.ListTagsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListTagsRequest): - request = datacatalog.ListTagsRequest(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_tags] - - # 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.ListTagsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets an access control policy for a resource. Replaces any - existing policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method sets policies only within Data Catalog and - can't be used to manage policies in BigQuery, Pub/Sub, Dataproc - Metastore, and any external Google Cloud Platform resources - synced with the Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. - - May return: - - - A\ ``NOT_FOUND`` error if the resource doesn't exist or you - don't have the permission to view it. - - An empty policy if the resource exists but doesn't have a set - policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method doesn't get policies from Google Cloud - Platform resources ingested into Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Gets your permissions on a resource. - Returns an empty set of permissions if the resource - doesn't exist. - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method gets policies only within Data Catalog - and can't be used to get policies from BigQuery, - Pub/Sub, Dataproc Metastore, and any external Google - Cloud Platform resources ingested into Data Catalog. - No Google IAM permissions are required to call this - method. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataCatalogClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py deleted file mode 100644 index 20096de6..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/pagers.py +++ /dev/null @@ -1,508 +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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import search -from google.cloud.datacatalog_v1.types import tags - - -class SearchCatalogPager: - """A pager for iterating through ``search_catalog`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchCatalog`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` - 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[..., datacatalog.SearchCatalogResponse], - request: datacatalog.SearchCatalogRequest, - response: datacatalog.SearchCatalogResponse, - *, - 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.datacatalog_v1.types.SearchCatalogRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.SearchCatalogResponse): - 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 = datacatalog.SearchCatalogRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.SearchCatalogResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search.SearchCatalogResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchCatalogAsyncPager: - """A pager for iterating through ``search_catalog`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchCatalog`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.SearchCatalogResponse` - 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[datacatalog.SearchCatalogResponse]], - request: datacatalog.SearchCatalogRequest, - response: datacatalog.SearchCatalogResponse, - *, - 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.datacatalog_v1.types.SearchCatalogRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.SearchCatalogResponse): - 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 = datacatalog.SearchCatalogRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.SearchCatalogResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[search.SearchCatalogResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntryGroupsPager: - """A pager for iterating through ``list_entry_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entry_groups`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntryGroups`` requests and continue to iterate - through the ``entry_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` - 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[..., datacatalog.ListEntryGroupsResponse], - request: datacatalog.ListEntryGroupsRequest, - response: datacatalog.ListEntryGroupsResponse, - *, - 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.datacatalog_v1.types.ListEntryGroupsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListEntryGroupsResponse): - 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 = datacatalog.ListEntryGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListEntryGroupsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[datacatalog.EntryGroup]: - for page in self.pages: - yield from page.entry_groups - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntryGroupsAsyncPager: - """A pager for iterating through ``list_entry_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entry_groups`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntryGroups`` requests and continue to iterate - through the ``entry_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListEntryGroupsResponse` - 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[datacatalog.ListEntryGroupsResponse]], - request: datacatalog.ListEntryGroupsRequest, - response: datacatalog.ListEntryGroupsResponse, - *, - 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.datacatalog_v1.types.ListEntryGroupsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListEntryGroupsResponse): - 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 = datacatalog.ListEntryGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListEntryGroupsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[datacatalog.EntryGroup]: - async def async_generator(): - async for page in self.pages: - for response in page.entry_groups: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntriesPager: - """A pager for iterating through ``list_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` - 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[..., datacatalog.ListEntriesResponse], - request: datacatalog.ListEntriesRequest, - response: datacatalog.ListEntriesResponse, - *, - 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.datacatalog_v1.types.ListEntriesRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListEntriesResponse): - 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 = datacatalog.ListEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListEntriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[datacatalog.Entry]: - for page in self.pages: - yield from page.entries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntriesAsyncPager: - """A pager for iterating through ``list_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListEntriesResponse` - 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[datacatalog.ListEntriesResponse]], - request: datacatalog.ListEntriesRequest, - response: datacatalog.ListEntriesResponse, - *, - 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.datacatalog_v1.types.ListEntriesRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListEntriesResponse): - 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 = datacatalog.ListEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListEntriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[datacatalog.Entry]: - async def async_generator(): - async for page in self.pages: - for response in page.entries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagsPager: - """A pager for iterating through ``list_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tags`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTags`` requests and continue to iterate - through the ``tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` - 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[..., datacatalog.ListTagsResponse], - request: datacatalog.ListTagsRequest, - response: datacatalog.ListTagsResponse, - *, - 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.datacatalog_v1.types.ListTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListTagsResponse): - 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 = datacatalog.ListTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tags.Tag]: - for page in self.pages: - yield from page.tags - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagsAsyncPager: - """A pager for iterating through ``list_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tags`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTags`` requests and continue to iterate - through the ``tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListTagsResponse` - 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[datacatalog.ListTagsResponse]], - request: datacatalog.ListTagsRequest, - response: datacatalog.ListTagsResponse, - *, - 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.datacatalog_v1.types.ListTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListTagsResponse): - 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 = datacatalog.ListTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[tags.Tag]: - async def async_generator(): - async for page in self.pages: - for response in page.tags: - 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/datacatalog_v1/services/data_catalog/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/__init__.py deleted file mode 100644 index f8baae0c..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/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 DataCatalogTransport -from .grpc import DataCatalogGrpcTransport -from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]] -_transport_registry['grpc'] = DataCatalogGrpcTransport -_transport_registry['grpc_asyncio'] = DataCatalogGrpcAsyncIOTransport - -__all__ = ( - 'DataCatalogTransport', - 'DataCatalogGrpcTransport', - 'DataCatalogGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py deleted file mode 100644 index a6522705..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/base.py +++ /dev/null @@ -1,576 +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 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.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -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-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class DataCatalogTransport(abc.ABC): - """Abstract transport class for DataCatalog.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search_catalog: gapic_v1.method.wrap_method( - self.search_catalog, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_entry_group: gapic_v1.method.wrap_method( - self.create_entry_group, - default_timeout=None, - client_info=client_info, - ), - self.get_entry_group: gapic_v1.method.wrap_method( - self.get_entry_group, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_entry_group: gapic_v1.method.wrap_method( - self.update_entry_group, - default_timeout=None, - client_info=client_info, - ), - self.delete_entry_group: gapic_v1.method.wrap_method( - self.delete_entry_group, - default_timeout=None, - client_info=client_info, - ), - self.list_entry_groups: gapic_v1.method.wrap_method( - self.list_entry_groups, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_entry: gapic_v1.method.wrap_method( - self.create_entry, - default_timeout=None, - client_info=client_info, - ), - self.update_entry: gapic_v1.method.wrap_method( - self.update_entry, - default_timeout=None, - client_info=client_info, - ), - self.delete_entry: gapic_v1.method.wrap_method( - self.delete_entry, - default_timeout=None, - client_info=client_info, - ), - self.get_entry: gapic_v1.method.wrap_method( - self.get_entry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.lookup_entry: gapic_v1.method.wrap_method( - self.lookup_entry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_entries: gapic_v1.method.wrap_method( - self.list_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag_template: gapic_v1.method.wrap_method( - self.create_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.get_tag_template: gapic_v1.method.wrap_method( - self.get_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.update_tag_template: gapic_v1.method.wrap_method( - self.update_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag_template: gapic_v1.method.wrap_method( - self.delete_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.create_tag_template_field: gapic_v1.method.wrap_method( - self.create_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.update_tag_template_field: gapic_v1.method.wrap_method( - self.update_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.rename_tag_template_field: gapic_v1.method.wrap_method( - self.rename_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.rename_tag_template_field_enum_value: gapic_v1.method.wrap_method( - self.rename_tag_template_field_enum_value, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag_template_field: gapic_v1.method.wrap_method( - self.delete_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.create_tag: gapic_v1.method.wrap_method( - self.create_tag, - default_timeout=None, - client_info=client_info, - ), - self.update_tag: gapic_v1.method.wrap_method( - self.update_tag, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag: gapic_v1.method.wrap_method( - self.delete_tag, - default_timeout=None, - client_info=client_info, - ), - self.list_tags: gapic_v1.method.wrap_method( - self.list_tags, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - Union[ - datacatalog.SearchCatalogResponse, - Awaitable[datacatalog.SearchCatalogResponse] - ]]: - raise NotImplementedError() - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - Union[ - datacatalog.ListEntryGroupsResponse, - Awaitable[datacatalog.ListEntryGroupsResponse] - ]]: - raise NotImplementedError() - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - Union[ - datacatalog.ListEntriesResponse, - Awaitable[datacatalog.ListEntriesResponse] - ]]: - raise NotImplementedError() - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def rename_tag_template_field_enum_value(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldEnumValueRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - Union[ - tags.Tag, - Awaitable[tags.Tag] - ]]: - raise NotImplementedError() - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - Union[ - tags.Tag, - Awaitable[tags.Tag] - ]]: - raise NotImplementedError() - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - Union[ - datacatalog.ListTagsResponse, - Awaitable[datacatalog.ListTagsResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DataCatalogTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py deleted file mode 100644 index 4132c37e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc.py +++ /dev/null @@ -1,1161 +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.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO - - -class DataCatalogGrpcTransport(DataCatalogTransport): - """gRPC backend transport for DataCatalog. - - Data Catalog API service allows you to discover, understand, - and manage your data. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - datacatalog.SearchCatalogResponse]: - r"""Return a callable for the search catalog method over gRPC. - - Searches Data Catalog for multiple resources like entries and - tags that match a query. - - This is a [Custom Method] - (https://cloud.google.com/apis/design/custom_methods) that - doesn't return all information on a resource, only its ID and - high level fields. To get more information, you can subsequently - call specific get methods. - - Note: Data Catalog search queries don't guarantee full recall. - Results that match your query might not be returned, even in - subsequent result pages. Additionally, returned (and not - returned) results can vary if you repeat search queries. - - For more information, see [Data Catalog search syntax] - (https://cloud.google.com/data-catalog/docs/how-to/search-reference). - - Returns: - Callable[[~.SearchCatalogRequest], - ~.SearchCatalogResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_catalog' not in self._stubs: - self._stubs['search_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/SearchCatalog', - request_serializer=datacatalog.SearchCatalogRequest.serialize, - response_deserializer=datacatalog.SearchCatalogResponse.deserialize, - ) - return self._stubs['search_catalog'] - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the create entry group method over gRPC. - - Creates an entry group. - - An entry group contains logically related entries together with - `Cloud Identity and Access - Management `__ policies. These - policies specify users who can create, edit, and view entries - within entry groups. - - Data Catalog automatically creates entry groups with names that - start with the ``@`` symbol for the following resources: - - - BigQuery entries (``@bigquery``) - - Pub/Sub topics (``@pubsub``) - - Dataproc Metastore services - (``@dataproc_metastore_{SERVICE_NAME_HASH}``) - - You can create your own entry groups for Cloud Storage fileset - entries and custom entries together with the corresponding IAM - policies. User-created entry groups can't contain the ``@`` - symbol, it is reserved for automatically created groups. - - Entry groups, like entries, can be searched. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.CreateEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateEntryGroup', - request_serializer=datacatalog.CreateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['create_entry_group'] - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the get entry group method over gRPC. - - Gets an entry group. - - Returns: - Callable[[~.GetEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetEntryGroup', - request_serializer=datacatalog.GetEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['get_entry_group'] - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the update entry group method over gRPC. - - Updates an entry group. - - You must enable the Data Catalog API in the project identified - by the ``entry_group.name`` parameter. For more information, see - `Data Catalog resource - project `__. - - Returns: - Callable[[~.UpdateEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntryGroup', - request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['update_entry_group'] - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entry group method over gRPC. - - Deletes an entry group. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteEntryGroupRequest], - ~.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_entry_group' not in self._stubs: - self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntryGroup', - request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry_group'] - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - datacatalog.ListEntryGroupsResponse]: - r"""Return a callable for the list entry groups method over gRPC. - - Lists entry groups. - - Returns: - Callable[[~.ListEntryGroupsRequest], - ~.ListEntryGroupsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: - self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListEntryGroups', - request_serializer=datacatalog.ListEntryGroupsRequest.serialize, - response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, - ) - return self._stubs['list_entry_groups'] - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the create entry method over gRPC. - - Creates an entry. - - You can create entries only with 'FILESET', 'CLUSTER', - 'DATA_STREAM', or custom types. Data Catalog automatically - creates entries with other types during metadata ingestion from - integrated systems. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - An entry group can have a maximum of 100,000 entries. - - Returns: - Callable[[~.CreateEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['create_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateEntry', - request_serializer=datacatalog.CreateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['create_entry'] - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the update entry method over gRPC. - - Updates an existing entry. - - You must enable the Data Catalog API in the project identified - by the ``entry.name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.UpdateEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['update_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntry', - request_serializer=datacatalog.UpdateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['update_entry'] - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entry method over gRPC. - - Deletes an existing entry. - - You can delete only the entries created by the - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] - method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteEntryRequest], - ~.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_entry' not in self._stubs: - self._stubs['delete_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntry', - request_serializer=datacatalog.DeleteEntryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry'] - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the get entry method over gRPC. - - Gets an entry. - - Returns: - Callable[[~.GetEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['get_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetEntry', - request_serializer=datacatalog.GetEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['get_entry'] - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the lookup entry method over gRPC. - - Gets an entry by its target resource name. - The resource name comes from the source Google Cloud - Platform service. - - Returns: - Callable[[~.LookupEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_entry' not in self._stubs: - self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/LookupEntry', - request_serializer=datacatalog.LookupEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['lookup_entry'] - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - datacatalog.ListEntriesResponse]: - r"""Return a callable for the list entries method over gRPC. - - Lists entries. - - Note: Currently, this method can list only custom entries. To - get a list of both custom and automatically created entries, use - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Returns: - Callable[[~.ListEntriesRequest], - ~.ListEntriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entries' not in self._stubs: - self._stubs['list_entries'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListEntries', - request_serializer=datacatalog.ListEntriesRequest.serialize, - response_deserializer=datacatalog.ListEntriesResponse.deserialize, - ) - return self._stubs['list_entries'] - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the create tag template method over gRPC. - - Creates a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Returns: - Callable[[~.CreateTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplate', - request_serializer=datacatalog.CreateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['create_tag_template'] - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the get tag template method over gRPC. - - Gets a tag template. - - Returns: - Callable[[~.GetTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetTagTemplate', - request_serializer=datacatalog.GetTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['get_tag_template'] - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the update tag template method over gRPC. - - Updates a tag template. - - You can't update template fields with this method. These fields - are separate resources with their own create, update, and delete - methods. - - You must enable the Data Catalog API in the project identified - by the ``tag_template.name`` parameter. For more information, - see `Data Catalog resource - project `__. - - Returns: - Callable[[~.UpdateTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplate', - request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['update_tag_template'] - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag template method over gRPC. - - Deletes a tag template and all tags that use it. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteTagTemplateRequest], - ~.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_tag_template' not in self._stubs: - self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplate', - request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template'] - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the create tag template field method over gRPC. - - Creates a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.CreateTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplateField', - request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['create_tag_template_field'] - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the update tag template field method over gRPC. - - Updates a field in a tag template. - - You can't update the field type with this method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.UpdateTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplateField', - request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['update_tag_template_field'] - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the rename tag template field method over gRPC. - - Renames a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Returns: - Callable[[~.RenameTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field' not in self._stubs: - self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateField', - request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field'] - - @property - def rename_tag_template_field_enum_value(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldEnumValueRequest], - tags.TagTemplateField]: - r"""Return a callable for the rename tag template field enum - value method over gRPC. - - Renames an enum value in a tag template. - Within a single enum field, enum values must be unique. - - Returns: - Callable[[~.RenameTagTemplateFieldEnumValueRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field_enum_value' not in self._stubs: - self._stubs['rename_tag_template_field_enum_value'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateFieldEnumValue', - request_serializer=datacatalog.RenameTagTemplateFieldEnumValueRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field_enum_value'] - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag template field method over gRPC. - - Deletes a field in a tag template and all uses of this field - from the tags based on this template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteTagTemplateFieldRequest], - ~.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_tag_template_field' not in self._stubs: - self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplateField', - request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template_field'] - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - tags.Tag]: - r"""Return a callable for the create tag method over gRPC. - - Creates a tag and assigns it to: - - - An [Entry][google.cloud.datacatalog.v1.Entry] if the method - name is - ``projects.locations.entryGroups.entries.tags.create``. - - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the - method name is - ``projects.locations.entryGroups.tags.create``. - - Note: The project identified by the ``parent`` parameter for the - [tag] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) - and the [tag template] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) - used to create the tag must be in the same organization. - - Returns: - Callable[[~.CreateTagRequest], - ~.Tag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['create_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTag', - request_serializer=datacatalog.CreateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['create_tag'] - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - tags.Tag]: - r"""Return a callable for the update tag method over gRPC. - - Updates an existing tag. - - Returns: - Callable[[~.UpdateTagRequest], - ~.Tag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['update_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTag', - request_serializer=datacatalog.UpdateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['update_tag'] - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag method over gRPC. - - Deletes a tag. - - Returns: - Callable[[~.DeleteTagRequest], - ~.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_tag' not in self._stubs: - self._stubs['delete_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTag', - request_serializer=datacatalog.DeleteTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag'] - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - datacatalog.ListTagsResponse]: - r"""Return a callable for the list tags method over gRPC. - - Lists tags assigned to an - [Entry][google.cloud.datacatalog.v1.Entry]. - - Returns: - Callable[[~.ListTagsRequest], - ~.ListTagsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tags' not in self._stubs: - self._stubs['list_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListTags', - request_serializer=datacatalog.ListTagsRequest.serialize, - response_deserializer=datacatalog.ListTagsResponse.deserialize, - ) - return self._stubs['list_tags'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets an access control policy for a resource. Replaces any - existing policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method sets policies only within Data Catalog and - can't be used to manage policies in BigQuery, Pub/Sub, Dataproc - Metastore, and any external Google Cloud Platform resources - synced with the Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. - - May return: - - - A\ ``NOT_FOUND`` error if the resource doesn't exist or you - don't have the permission to view it. - - An empty policy if the resource exists but doesn't have a set - policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method doesn't get policies from Google Cloud - Platform resources ingested into Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Gets your permissions on a resource. - Returns an empty set of permissions if the resource - doesn't exist. - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method gets policies only within Data Catalog - and can't be used to get policies from BigQuery, - Pub/Sub, Dataproc Metastore, and any external Google - Cloud Platform resources ingested into Data Catalog. - No Google IAM permissions are required to call this - method. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'DataCatalogGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py deleted file mode 100644 index e68d47aa..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/data_catalog/transports/grpc_asyncio.py +++ /dev/null @@ -1,1165 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .grpc import DataCatalogGrpcTransport - - -class DataCatalogGrpcAsyncIOTransport(DataCatalogTransport): - """gRPC AsyncIO backend transport for DataCatalog. - - Data Catalog API service allows you to discover, understand, - and manage your data. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - Awaitable[datacatalog.SearchCatalogResponse]]: - r"""Return a callable for the search catalog method over gRPC. - - Searches Data Catalog for multiple resources like entries and - tags that match a query. - - This is a [Custom Method] - (https://cloud.google.com/apis/design/custom_methods) that - doesn't return all information on a resource, only its ID and - high level fields. To get more information, you can subsequently - call specific get methods. - - Note: Data Catalog search queries don't guarantee full recall. - Results that match your query might not be returned, even in - subsequent result pages. Additionally, returned (and not - returned) results can vary if you repeat search queries. - - For more information, see [Data Catalog search syntax] - (https://cloud.google.com/data-catalog/docs/how-to/search-reference). - - Returns: - Callable[[~.SearchCatalogRequest], - Awaitable[~.SearchCatalogResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_catalog' not in self._stubs: - self._stubs['search_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/SearchCatalog', - request_serializer=datacatalog.SearchCatalogRequest.serialize, - response_deserializer=datacatalog.SearchCatalogResponse.deserialize, - ) - return self._stubs['search_catalog'] - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the create entry group method over gRPC. - - Creates an entry group. - - An entry group contains logically related entries together with - `Cloud Identity and Access - Management `__ policies. These - policies specify users who can create, edit, and view entries - within entry groups. - - Data Catalog automatically creates entry groups with names that - start with the ``@`` symbol for the following resources: - - - BigQuery entries (``@bigquery``) - - Pub/Sub topics (``@pubsub``) - - Dataproc Metastore services - (``@dataproc_metastore_{SERVICE_NAME_HASH}``) - - You can create your own entry groups for Cloud Storage fileset - entries and custom entries together with the corresponding IAM - policies. User-created entry groups can't contain the ``@`` - symbol, it is reserved for automatically created groups. - - Entry groups, like entries, can be searched. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.CreateEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateEntryGroup', - request_serializer=datacatalog.CreateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['create_entry_group'] - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the get entry group method over gRPC. - - Gets an entry group. - - Returns: - Callable[[~.GetEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetEntryGroup', - request_serializer=datacatalog.GetEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['get_entry_group'] - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the update entry group method over gRPC. - - Updates an entry group. - - You must enable the Data Catalog API in the project identified - by the ``entry_group.name`` parameter. For more information, see - `Data Catalog resource - project `__. - - Returns: - Callable[[~.UpdateEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntryGroup', - request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['update_entry_group'] - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete entry group method over gRPC. - - Deletes an entry group. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteEntryGroupRequest], - 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_entry_group' not in self._stubs: - self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntryGroup', - request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry_group'] - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - Awaitable[datacatalog.ListEntryGroupsResponse]]: - r"""Return a callable for the list entry groups method over gRPC. - - Lists entry groups. - - Returns: - Callable[[~.ListEntryGroupsRequest], - Awaitable[~.ListEntryGroupsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: - self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListEntryGroups', - request_serializer=datacatalog.ListEntryGroupsRequest.serialize, - response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, - ) - return self._stubs['list_entry_groups'] - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the create entry method over gRPC. - - Creates an entry. - - You can create entries only with 'FILESET', 'CLUSTER', - 'DATA_STREAM', or custom types. Data Catalog automatically - creates entries with other types during metadata ingestion from - integrated systems. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - An entry group can have a maximum of 100,000 entries. - - Returns: - Callable[[~.CreateEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['create_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateEntry', - request_serializer=datacatalog.CreateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['create_entry'] - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the update entry method over gRPC. - - Updates an existing entry. - - You must enable the Data Catalog API in the project identified - by the ``entry.name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.UpdateEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['update_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateEntry', - request_serializer=datacatalog.UpdateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['update_entry'] - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete entry method over gRPC. - - Deletes an existing entry. - - You can delete only the entries created by the - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry] - method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteEntryRequest], - 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_entry' not in self._stubs: - self._stubs['delete_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteEntry', - request_serializer=datacatalog.DeleteEntryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry'] - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the get entry method over gRPC. - - Gets an entry. - - Returns: - Callable[[~.GetEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['get_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetEntry', - request_serializer=datacatalog.GetEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['get_entry'] - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the lookup entry method over gRPC. - - Gets an entry by its target resource name. - The resource name comes from the source Google Cloud - Platform service. - - Returns: - Callable[[~.LookupEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_entry' not in self._stubs: - self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/LookupEntry', - request_serializer=datacatalog.LookupEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['lookup_entry'] - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - Awaitable[datacatalog.ListEntriesResponse]]: - r"""Return a callable for the list entries method over gRPC. - - Lists entries. - - Note: Currently, this method can list only custom entries. To - get a list of both custom and automatically created entries, use - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Returns: - Callable[[~.ListEntriesRequest], - Awaitable[~.ListEntriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entries' not in self._stubs: - self._stubs['list_entries'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListEntries', - request_serializer=datacatalog.ListEntriesRequest.serialize, - response_deserializer=datacatalog.ListEntriesResponse.deserialize, - ) - return self._stubs['list_entries'] - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the create tag template method over gRPC. - - Creates a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Returns: - Callable[[~.CreateTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplate', - request_serializer=datacatalog.CreateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['create_tag_template'] - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the get tag template method over gRPC. - - Gets a tag template. - - Returns: - Callable[[~.GetTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetTagTemplate', - request_serializer=datacatalog.GetTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['get_tag_template'] - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the update tag template method over gRPC. - - Updates a tag template. - - You can't update template fields with this method. These fields - are separate resources with their own create, update, and delete - methods. - - You must enable the Data Catalog API in the project identified - by the ``tag_template.name`` parameter. For more information, - see `Data Catalog resource - project `__. - - Returns: - Callable[[~.UpdateTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplate', - request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['update_tag_template'] - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag template method over gRPC. - - Deletes a tag template and all tags that use it. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteTagTemplateRequest], - 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_tag_template' not in self._stubs: - self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplate', - request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template'] - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the create tag template field method over gRPC. - - Creates a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``parent`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.CreateTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTagTemplateField', - request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['create_tag_template_field'] - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the update tag template field method over gRPC. - - Updates a field in a tag template. - - You can't update the field type with this method. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.UpdateTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTagTemplateField', - request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['update_tag_template_field'] - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the rename tag template field method over gRPC. - - Renames a field in a tag template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see [Data - Catalog resource project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project). - - Returns: - Callable[[~.RenameTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field' not in self._stubs: - self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateField', - request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field'] - - @property - def rename_tag_template_field_enum_value(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldEnumValueRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the rename tag template field enum - value method over gRPC. - - Renames an enum value in a tag template. - Within a single enum field, enum values must be unique. - - Returns: - Callable[[~.RenameTagTemplateFieldEnumValueRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field_enum_value' not in self._stubs: - self._stubs['rename_tag_template_field_enum_value'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/RenameTagTemplateFieldEnumValue', - request_serializer=datacatalog.RenameTagTemplateFieldEnumValueRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field_enum_value'] - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag template field method over gRPC. - - Deletes a field in a tag template and all uses of this field - from the tags based on this template. - - You must enable the Data Catalog API in the project identified - by the ``name`` parameter. For more information, see `Data - Catalog resource - project `__. - - Returns: - Callable[[~.DeleteTagTemplateFieldRequest], - 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_tag_template_field' not in self._stubs: - self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTagTemplateField', - request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template_field'] - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - Awaitable[tags.Tag]]: - r"""Return a callable for the create tag method over gRPC. - - Creates a tag and assigns it to: - - - An [Entry][google.cloud.datacatalog.v1.Entry] if the method - name is - ``projects.locations.entryGroups.entries.tags.create``. - - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the - method name is - ``projects.locations.entryGroups.tags.create``. - - Note: The project identified by the ``parent`` parameter for the - [tag] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) - and the [tag template] - (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) - used to create the tag must be in the same organization. - - Returns: - Callable[[~.CreateTagRequest], - Awaitable[~.Tag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['create_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/CreateTag', - request_serializer=datacatalog.CreateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['create_tag'] - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - Awaitable[tags.Tag]]: - r"""Return a callable for the update tag method over gRPC. - - Updates an existing tag. - - Returns: - Callable[[~.UpdateTagRequest], - Awaitable[~.Tag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['update_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/UpdateTag', - request_serializer=datacatalog.UpdateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['update_tag'] - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag method over gRPC. - - Deletes a tag. - - Returns: - Callable[[~.DeleteTagRequest], - 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_tag' not in self._stubs: - self._stubs['delete_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/DeleteTag', - request_serializer=datacatalog.DeleteTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag'] - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - Awaitable[datacatalog.ListTagsResponse]]: - r"""Return a callable for the list tags method over gRPC. - - Lists tags assigned to an - [Entry][google.cloud.datacatalog.v1.Entry]. - - Returns: - Callable[[~.ListTagsRequest], - Awaitable[~.ListTagsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tags' not in self._stubs: - self._stubs['list_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/ListTags', - request_serializer=datacatalog.ListTagsRequest.serialize, - response_deserializer=datacatalog.ListTagsResponse.deserialize, - ) - return self._stubs['list_tags'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets an access control policy for a resource. Replaces any - existing policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method sets policies only within Data Catalog and - can't be used to manage policies in BigQuery, Pub/Sub, Dataproc - Metastore, and any external Google Cloud Platform resources - synced with the Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. - - May return: - - - A\ ``NOT_FOUND`` error if the resource doesn't exist or you - don't have the permission to view it. - - An empty policy if the resource exists but doesn't have a set - policy. - - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method doesn't get policies from Google Cloud - Platform resources ingested into Data Catalog. - - To call this method, you must have the following Google IAM - permissions: - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Gets your permissions on a resource. - Returns an empty set of permissions if the resource - doesn't exist. - Supported resources are: - - - Tag templates - - Entry groups - - Note: This method gets policies only within Data Catalog - and can't be used to get policies from BigQuery, - Pub/Sub, Dataproc Metastore, and any external Google - Cloud Platform resources ingested into Data Catalog. - No Google IAM permissions are required to call this - method. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.DataCatalog/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DataCatalogGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__init__.py deleted file mode 100644 index 3d4e08a0..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/__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 PolicyTagManagerClient -from .async_client import PolicyTagManagerAsyncClient - -__all__ = ( - 'PolicyTagManagerClient', - 'PolicyTagManagerAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py deleted file mode 100644 index a0448861..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/async_client.py +++ /dev/null @@ -1,1300 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport -from .client import PolicyTagManagerClient - - -class PolicyTagManagerAsyncClient: - """Policy Tag Manager API service allows you to manage your - policy tags and taxonomies. - - Policy tags are used to tag BigQuery columns and apply - additional access control policies. A taxonomy is a hierarchical - grouping of policy tags that classify data along a common axis. - """ - - _client: PolicyTagManagerClient - - DEFAULT_ENDPOINT = PolicyTagManagerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PolicyTagManagerClient.DEFAULT_MTLS_ENDPOINT - - policy_tag_path = staticmethod(PolicyTagManagerClient.policy_tag_path) - parse_policy_tag_path = staticmethod(PolicyTagManagerClient.parse_policy_tag_path) - taxonomy_path = staticmethod(PolicyTagManagerClient.taxonomy_path) - parse_taxonomy_path = staticmethod(PolicyTagManagerClient.parse_taxonomy_path) - common_billing_account_path = staticmethod(PolicyTagManagerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PolicyTagManagerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PolicyTagManagerClient.common_folder_path) - parse_common_folder_path = staticmethod(PolicyTagManagerClient.parse_common_folder_path) - common_organization_path = staticmethod(PolicyTagManagerClient.common_organization_path) - parse_common_organization_path = staticmethod(PolicyTagManagerClient.parse_common_organization_path) - common_project_path = staticmethod(PolicyTagManagerClient.common_project_path) - parse_common_project_path = staticmethod(PolicyTagManagerClient.parse_common_project_path) - common_location_path = staticmethod(PolicyTagManagerClient.common_location_path) - parse_common_location_path = staticmethod(PolicyTagManagerClient.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: - PolicyTagManagerAsyncClient: The constructed client. - """ - return PolicyTagManagerClient.from_service_account_info.__func__(PolicyTagManagerAsyncClient, 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: - PolicyTagManagerAsyncClient: The constructed client. - """ - return PolicyTagManagerClient.from_service_account_file.__func__(PolicyTagManagerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PolicyTagManagerTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PolicyTagManagerClient).get_transport_class, type(PolicyTagManagerClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PolicyTagManagerTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager 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, ~.PolicyTagManagerTransport]): 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 = PolicyTagManagerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_taxonomy(self, - request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, - *, - parent: str = None, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Creates a taxonomy in a specified project. - The taxonomy is initially empty, that is, it doesn't - contain policy tags. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTaxonomyRequest, dict]): - The request object. Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. - parent (:class:`str`): - Required. Resource name of the - project that the taxonomy will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - taxonomy (:class:`google.cloud.datacatalog_v1.types.Taxonomy`): - The taxonomy to create. - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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, taxonomy]) - if request is 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 = policytagmanager.CreateTaxonomyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if taxonomy is not None: - request.taxonomy = taxonomy - - # 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_taxonomy, - default_timeout=None, - client_info=DEFAULT_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 delete_taxonomy(self, - request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a taxonomy, including all policy tags in this - taxonomy, their associated policies, and the policy tags - references from BigQuery columns. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTaxonomyRequest, dict]): - The request object. Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. - name (:class:`str`): - Required. Resource name of the - taxonomy to delete. - Note: All policy tags in this taxonomy - are also deleted. - - 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 = policytagmanager.DeleteTaxonomyRequest(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_taxonomy, - default_timeout=None, - client_info=DEFAULT_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 update_taxonomy(self, - request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, - *, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Updates a taxonomy, including its display name, - description, and activated policy types. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTaxonomyRequest, dict]): - The request object. Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. - taxonomy (:class:`google.cloud.datacatalog_v1.types.Taxonomy`): - The taxonomy to update. You can - update only its description, display - name, and activated policy types. - - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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([taxonomy]) - if request is 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 = policytagmanager.UpdateTaxonomyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if taxonomy is not None: - request.taxonomy = taxonomy - - # 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_taxonomy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("taxonomy.name", request.taxonomy.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_taxonomies(self, - request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTaxonomiesAsyncPager: - r"""Lists all taxonomies in a project in a particular - location that you have a permission to view. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListTaxonomiesRequest, dict]): - The request object. Request message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - parent (:class:`str`): - Required. Resource name of the - project to list the taxonomies of. - - 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.datacatalog_v1.services.policy_tag_manager.pagers.ListTaxonomiesAsyncPager: - Response message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - - 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 = policytagmanager.ListTaxonomiesRequest(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_taxonomies, - default_timeout=None, - client_info=DEFAULT_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.ListTaxonomiesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_taxonomy(self, - request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Gets a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetTaxonomyRequest, dict]): - The request object. Request message for - [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. - name (:class:`str`): - Required. Resource name of the - taxonomy to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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 = policytagmanager.GetTaxonomyRequest(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_taxonomy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_policy_tag(self, - request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, - *, - parent: str = None, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Creates a policy tag in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreatePolicyTagRequest, dict]): - The request object. Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. - parent (:class:`str`): - Required. Resource name of the - taxonomy that the policy tag will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - policy_tag (:class:`google.cloud.datacatalog_v1.types.PolicyTag`): - The policy tag to create. - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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, policy_tag]) - if request is 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 = policytagmanager.CreatePolicyTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if policy_tag is not None: - request.policy_tag = policy_tag - - # 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_policy_tag, - default_timeout=None, - client_info=DEFAULT_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 delete_policy_tag(self, - request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a policy tag together with the following: - - - All of its descendant policy tags, if any - - Policies associated with the policy tag and its descendants - - References from BigQuery table schema of the policy tag and - its descendants - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeletePolicyTagRequest, dict]): - The request object. Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. - name (:class:`str`): - Required. Resource name of the policy - tag to delete. - Note: All of its descendant policy tags - are also deleted. - - 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 = policytagmanager.DeletePolicyTagRequest(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_policy_tag, - default_timeout=None, - client_info=DEFAULT_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 update_policy_tag(self, - request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, - *, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Updates a policy tag, including its display - name, description, and parent policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdatePolicyTagRequest, dict]): - The request object. Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. - policy_tag (:class:`google.cloud.datacatalog_v1.types.PolicyTag`): - The policy tag to update. You can - update only its description, display - name, and parent policy tag fields. - - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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([policy_tag]) - if request is 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 = policytagmanager.UpdatePolicyTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if policy_tag is not None: - request.policy_tag = policy_tag - - # 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_policy_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("policy_tag.name", request.policy_tag.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_policy_tags(self, - request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPolicyTagsAsyncPager: - r"""Lists all policy tags in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListPolicyTagsRequest, dict]): - The request object. Request message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - parent (:class:`str`): - Required. Resource name of the - taxonomy to list the policy tags of. - - 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.datacatalog_v1.services.policy_tag_manager.pagers.ListPolicyTagsAsyncPager: - Response message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - - 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 = policytagmanager.ListPolicyTagsRequest(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_policy_tags, - default_timeout=None, - client_info=DEFAULT_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.ListPolicyTagsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_policy_tag(self, - request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Gets a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetPolicyTagRequest, dict]): - The request object. Request message for - [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. - name (:class:`str`): - Required. Resource name of the policy - tag. - - 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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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 = policytagmanager.GetPolicyTagRequest(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_policy_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM policy for a policy tag or a taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM policy for a policy tag or a taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns your permissions on a specified policy tag or - taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py deleted file mode 100644 index c160511e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py +++ /dev/null @@ -1,1503 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PolicyTagManagerGrpcTransport -from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport - - -class PolicyTagManagerClientMeta(type): - """Metaclass for the PolicyTagManager 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[PolicyTagManagerTransport]] - _transport_registry["grpc"] = PolicyTagManagerGrpcTransport - _transport_registry["grpc_asyncio"] = PolicyTagManagerGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PolicyTagManagerTransport]: - """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 PolicyTagManagerClient(metaclass=PolicyTagManagerClientMeta): - """Policy Tag Manager API service allows you to manage your - policy tags and taxonomies. - - Policy tags are used to tag BigQuery columns and apply - additional access control policies. A taxonomy is a hierarchical - grouping of policy tags that classify data along a common axis. - """ - - @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 = "datacatalog.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: - PolicyTagManagerClient: 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: - PolicyTagManagerClient: 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) -> PolicyTagManagerTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def policy_tag_path(project: str,location: str,taxonomy: str,policy_tag: str,) -> str: - """Returns a fully-qualified policy_tag string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) - - @staticmethod - def parse_policy_tag_path(path: str) -> Dict[str,str]: - """Parses a policy_tag path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?P.+?)/policyTags/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: - """Returns a fully-qualified taxonomy string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - - @staticmethod - def parse_taxonomy_path(path: str) -> Dict[str,str]: - """Parses a taxonomy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager 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, PolicyTagManagerTransport]): 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, PolicyTagManagerTransport): - # transport is a PolicyTagManagerTransport 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=True, - ) - - def create_taxonomy(self, - request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, - *, - parent: str = None, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Creates a taxonomy in a specified project. - The taxonomy is initially empty, that is, it doesn't - contain policy tags. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreateTaxonomyRequest, dict]): - The request object. Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. - parent (str): - Required. Resource name of the - project that the taxonomy will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): - The taxonomy to create. - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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, taxonomy]) - if request is 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 policytagmanager.CreateTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.CreateTaxonomyRequest): - request = policytagmanager.CreateTaxonomyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if taxonomy is not None: - request.taxonomy = taxonomy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_taxonomy] - - # 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 delete_taxonomy(self, - request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a taxonomy, including all policy tags in this - taxonomy, their associated policies, and the policy tags - references from BigQuery columns. - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeleteTaxonomyRequest, dict]): - The request object. Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. - name (str): - Required. Resource name of the - taxonomy to delete. - Note: All policy tags in this taxonomy - are also deleted. - - 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 policytagmanager.DeleteTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.DeleteTaxonomyRequest): - request = policytagmanager.DeleteTaxonomyRequest(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_taxonomy] - - # Certain fields should be 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 update_taxonomy(self, - request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, - *, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Updates a taxonomy, including its display name, - description, and activated policy types. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdateTaxonomyRequest, dict]): - The request object. Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. - taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): - The taxonomy to update. You can - update only its description, display - name, and activated policy types. - - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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([taxonomy]) - if request is 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 policytagmanager.UpdateTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.UpdateTaxonomyRequest): - request = policytagmanager.UpdateTaxonomyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if taxonomy is not None: - request.taxonomy = taxonomy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_taxonomy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("taxonomy.name", request.taxonomy.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_taxonomies(self, - request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTaxonomiesPager: - r"""Lists all taxonomies in a project in a particular - location that you have a permission to view. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListTaxonomiesRequest, dict]): - The request object. Request message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - parent (str): - Required. Resource name of the - project to list the taxonomies of. - - 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.datacatalog_v1.services.policy_tag_manager.pagers.ListTaxonomiesPager: - Response message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - - 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 policytagmanager.ListTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.ListTaxonomiesRequest): - request = policytagmanager.ListTaxonomiesRequest(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_taxonomies] - - # 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.ListTaxonomiesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_taxonomy(self, - request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Gets a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetTaxonomyRequest, dict]): - The request object. Request message for - [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. - name (str): - Required. Resource name of the - taxonomy to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # 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 policytagmanager.GetTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.GetTaxonomyRequest): - request = policytagmanager.GetTaxonomyRequest(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_taxonomy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_policy_tag(self, - request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, - *, - parent: str = None, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Creates a policy tag in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.CreatePolicyTagRequest, dict]): - The request object. Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. - parent (str): - Required. Resource name of the - taxonomy that the policy tag will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): - The policy tag to create. - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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, policy_tag]) - if request is 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 policytagmanager.CreatePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.CreatePolicyTagRequest): - request = policytagmanager.CreatePolicyTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if policy_tag is not None: - request.policy_tag = policy_tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_policy_tag] - - # 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 delete_policy_tag(self, - request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a policy tag together with the following: - - - All of its descendant policy tags, if any - - Policies associated with the policy tag and its descendants - - References from BigQuery table schema of the policy tag and - its descendants - - Args: - request (Union[google.cloud.datacatalog_v1.types.DeletePolicyTagRequest, dict]): - The request object. Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. - name (str): - Required. Resource name of the policy - tag to delete. - Note: All of its descendant policy tags - are also deleted. - - 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 policytagmanager.DeletePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.DeletePolicyTagRequest): - request = policytagmanager.DeletePolicyTagRequest(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_policy_tag] - - # Certain fields should be 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 update_policy_tag(self, - request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, - *, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Updates a policy tag, including its display - name, description, and parent policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.UpdatePolicyTagRequest, dict]): - The request object. Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. - policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): - The policy tag to update. You can - update only its description, display - name, and parent policy tag fields. - - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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([policy_tag]) - if request is 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 policytagmanager.UpdatePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.UpdatePolicyTagRequest): - request = policytagmanager.UpdatePolicyTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if policy_tag is not None: - request.policy_tag = policy_tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_policy_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("policy_tag.name", request.policy_tag.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_policy_tags(self, - request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPolicyTagsPager: - r"""Lists all policy tags in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ListPolicyTagsRequest, dict]): - The request object. Request message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - parent (str): - Required. Resource name of the - taxonomy to list the policy tags of. - - 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.datacatalog_v1.services.policy_tag_manager.pagers.ListPolicyTagsPager: - Response message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - - 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 policytagmanager.ListPolicyTagsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.ListPolicyTagsRequest): - request = policytagmanager.ListPolicyTagsRequest(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_policy_tags] - - # 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.ListPolicyTagsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_policy_tag(self, - request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Gets a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1.types.GetPolicyTagRequest, dict]): - The request object. Request message for - [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. - name (str): - Required. Resource name of the policy - tag. - - 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.datacatalog_v1.types.PolicyTag: - Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For - example: - - :literal:`\` + Geolocation + LatLong + City + ZipCode`\ \` - - Where the "Geolocation" policy tag contains three - children. - - """ - # 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 policytagmanager.GetPolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.GetPolicyTagRequest): - request = policytagmanager.GetPolicyTagRequest(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_policy_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM policy for a policy tag or a taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM policy for a policy tag or a taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns your permissions on a specified policy tag or - taxonomy. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py deleted file mode 100644 index 512a1a12..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/pagers.py +++ /dev/null @@ -1,262 +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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.datacatalog_v1.types import policytagmanager - - -class ListTaxonomiesPager: - """A pager for iterating through ``list_taxonomies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``taxonomies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTaxonomies`` requests and continue to iterate - through the ``taxonomies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` - 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[..., policytagmanager.ListTaxonomiesResponse], - request: policytagmanager.ListTaxonomiesRequest, - response: policytagmanager.ListTaxonomiesResponse, - *, - 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.datacatalog_v1.types.ListTaxonomiesRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListTaxonomiesResponse): - 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 = policytagmanager.ListTaxonomiesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[policytagmanager.ListTaxonomiesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[policytagmanager.Taxonomy]: - for page in self.pages: - yield from page.taxonomies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTaxonomiesAsyncPager: - """A pager for iterating through ``list_taxonomies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``taxonomies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTaxonomies`` requests and continue to iterate - through the ``taxonomies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListTaxonomiesResponse` - 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[policytagmanager.ListTaxonomiesResponse]], - request: policytagmanager.ListTaxonomiesRequest, - response: policytagmanager.ListTaxonomiesResponse, - *, - 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.datacatalog_v1.types.ListTaxonomiesRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListTaxonomiesResponse): - 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 = policytagmanager.ListTaxonomiesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[policytagmanager.ListTaxonomiesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[policytagmanager.Taxonomy]: - async def async_generator(): - async for page in self.pages: - for response in page.taxonomies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPolicyTagsPager: - """A pager for iterating through ``list_policy_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``policy_tags`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPolicyTags`` requests and continue to iterate - through the ``policy_tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` - 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[..., policytagmanager.ListPolicyTagsResponse], - request: policytagmanager.ListPolicyTagsRequest, - response: policytagmanager.ListPolicyTagsResponse, - *, - 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.datacatalog_v1.types.ListPolicyTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListPolicyTagsResponse): - 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 = policytagmanager.ListPolicyTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[policytagmanager.ListPolicyTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[policytagmanager.PolicyTag]: - for page in self.pages: - yield from page.policy_tags - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPolicyTagsAsyncPager: - """A pager for iterating through ``list_policy_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``policy_tags`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPolicyTags`` requests and continue to iterate - through the ``policy_tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1.types.ListPolicyTagsResponse` - 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[policytagmanager.ListPolicyTagsResponse]], - request: policytagmanager.ListPolicyTagsRequest, - response: policytagmanager.ListPolicyTagsResponse, - *, - 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.datacatalog_v1.types.ListPolicyTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1.types.ListPolicyTagsResponse): - 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 = policytagmanager.ListPolicyTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[policytagmanager.ListPolicyTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[policytagmanager.PolicyTag]: - async def async_generator(): - async for page in self.pages: - for response in page.policy_tags: - 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/datacatalog_v1/services/policy_tag_manager/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/__init__.py deleted file mode 100644 index d76a9c05..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/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 PolicyTagManagerTransport -from .grpc import PolicyTagManagerGrpcTransport -from .grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerTransport]] -_transport_registry['grpc'] = PolicyTagManagerGrpcTransport -_transport_registry['grpc_asyncio'] = PolicyTagManagerGrpcAsyncIOTransport - -__all__ = ( - 'PolicyTagManagerTransport', - 'PolicyTagManagerGrpcTransport', - 'PolicyTagManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py deleted file mode 100644 index 8419877e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/base.py +++ /dev/null @@ -1,317 +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 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.datacatalog_v1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -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-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PolicyTagManagerTransport(abc.ABC): - """Abstract transport class for PolicyTagManager.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_taxonomy: gapic_v1.method.wrap_method( - self.create_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.delete_taxonomy: gapic_v1.method.wrap_method( - self.delete_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.update_taxonomy: gapic_v1.method.wrap_method( - self.update_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.list_taxonomies: gapic_v1.method.wrap_method( - self.list_taxonomies, - default_timeout=None, - client_info=client_info, - ), - self.get_taxonomy: gapic_v1.method.wrap_method( - self.get_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.create_policy_tag: gapic_v1.method.wrap_method( - self.create_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.delete_policy_tag: gapic_v1.method.wrap_method( - self.delete_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.update_policy_tag: gapic_v1.method.wrap_method( - self.update_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.list_policy_tags: gapic_v1.method.wrap_method( - self.list_policy_tags, - default_timeout=None, - client_info=client_info, - ), - self.get_policy_tag: gapic_v1.method.wrap_method( - self.get_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - Union[ - policytagmanager.ListTaxonomiesResponse, - Awaitable[policytagmanager.ListTaxonomiesResponse] - ]]: - raise NotImplementedError() - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - Union[ - policytagmanager.ListPolicyTagsResponse, - Awaitable[policytagmanager.ListPolicyTagsResponse] - ]]: - raise NotImplementedError() - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PolicyTagManagerTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py deleted file mode 100644 index 5d8abd85..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc.py +++ /dev/null @@ -1,587 +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.datacatalog_v1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO - - -class PolicyTagManagerGrpcTransport(PolicyTagManagerTransport): - """gRPC backend transport for PolicyTagManager. - - Policy Tag Manager API service allows you to manage your - policy tags and taxonomies. - - Policy tags are used to tag BigQuery columns and apply - additional access control policies. A taxonomy is a hierarchical - grouping of policy tags that classify data along a common axis. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the create taxonomy method over gRPC. - - Creates a taxonomy in a specified project. - The taxonomy is initially empty, that is, it doesn't - contain policy tags. - - Returns: - Callable[[~.CreateTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/CreateTaxonomy', - request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['create_taxonomy'] - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete taxonomy method over gRPC. - - Deletes a taxonomy, including all policy tags in this - taxonomy, their associated policies, and the policy tags - references from BigQuery columns. - - Returns: - Callable[[~.DeleteTaxonomyRequest], - ~.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_taxonomy' not in self._stubs: - self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/DeleteTaxonomy', - request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_taxonomy'] - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the update taxonomy method over gRPC. - - Updates a taxonomy, including its display name, - description, and activated policy types. - - Returns: - Callable[[~.UpdateTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/UpdateTaxonomy', - request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['update_taxonomy'] - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - policytagmanager.ListTaxonomiesResponse]: - r"""Return a callable for the list taxonomies method over gRPC. - - Lists all taxonomies in a project in a particular - location that you have a permission to view. - - Returns: - Callable[[~.ListTaxonomiesRequest], - ~.ListTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: - self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/ListTaxonomies', - request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, - response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, - ) - return self._stubs['list_taxonomies'] - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the get taxonomy method over gRPC. - - Gets a taxonomy. - - Returns: - Callable[[~.GetTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetTaxonomy', - request_serializer=policytagmanager.GetTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['get_taxonomy'] - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the create policy tag method over gRPC. - - Creates a policy tag in a taxonomy. - - Returns: - Callable[[~.CreatePolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/CreatePolicyTag', - request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['create_policy_tag'] - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete policy tag method over gRPC. - - Deletes a policy tag together with the following: - - - All of its descendant policy tags, if any - - Policies associated with the policy tag and its descendants - - References from BigQuery table schema of the policy tag and - its descendants - - Returns: - Callable[[~.DeletePolicyTagRequest], - ~.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_policy_tag' not in self._stubs: - self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/DeletePolicyTag', - request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_policy_tag'] - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the update policy tag method over gRPC. - - Updates a policy tag, including its display - name, description, and parent policy tag. - - Returns: - Callable[[~.UpdatePolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/UpdatePolicyTag', - request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['update_policy_tag'] - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - policytagmanager.ListPolicyTagsResponse]: - r"""Return a callable for the list policy tags method over gRPC. - - Lists all policy tags in a taxonomy. - - Returns: - Callable[[~.ListPolicyTagsRequest], - ~.ListPolicyTagsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: - self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/ListPolicyTags', - request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, - response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, - ) - return self._stubs['list_policy_tags'] - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the get policy tag method over gRPC. - - Gets a policy tag. - - Returns: - Callable[[~.GetPolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetPolicyTag', - request_serializer=policytagmanager.GetPolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['get_policy_tag'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM policy for a policy tag or a taxonomy. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM policy for a policy tag or a taxonomy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns your permissions on a specified policy tag or - taxonomy. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'PolicyTagManagerGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py deleted file mode 100644 index e5ffff41..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager/transports/grpc_asyncio.py +++ /dev/null @@ -1,591 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .grpc import PolicyTagManagerGrpcTransport - - -class PolicyTagManagerGrpcAsyncIOTransport(PolicyTagManagerTransport): - """gRPC AsyncIO backend transport for PolicyTagManager. - - Policy Tag Manager API service allows you to manage your - policy tags and taxonomies. - - Policy tags are used to tag BigQuery columns and apply - additional access control policies. A taxonomy is a hierarchical - grouping of policy tags that classify data along a common axis. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the create taxonomy method over gRPC. - - Creates a taxonomy in a specified project. - The taxonomy is initially empty, that is, it doesn't - contain policy tags. - - Returns: - Callable[[~.CreateTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/CreateTaxonomy', - request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['create_taxonomy'] - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete taxonomy method over gRPC. - - Deletes a taxonomy, including all policy tags in this - taxonomy, their associated policies, and the policy tags - references from BigQuery columns. - - Returns: - Callable[[~.DeleteTaxonomyRequest], - 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_taxonomy' not in self._stubs: - self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/DeleteTaxonomy', - request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_taxonomy'] - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the update taxonomy method over gRPC. - - Updates a taxonomy, including its display name, - description, and activated policy types. - - Returns: - Callable[[~.UpdateTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/UpdateTaxonomy', - request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['update_taxonomy'] - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - Awaitable[policytagmanager.ListTaxonomiesResponse]]: - r"""Return a callable for the list taxonomies method over gRPC. - - Lists all taxonomies in a project in a particular - location that you have a permission to view. - - Returns: - Callable[[~.ListTaxonomiesRequest], - Awaitable[~.ListTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: - self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/ListTaxonomies', - request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, - response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, - ) - return self._stubs['list_taxonomies'] - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the get taxonomy method over gRPC. - - Gets a taxonomy. - - Returns: - Callable[[~.GetTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetTaxonomy', - request_serializer=policytagmanager.GetTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['get_taxonomy'] - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the create policy tag method over gRPC. - - Creates a policy tag in a taxonomy. - - Returns: - Callable[[~.CreatePolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/CreatePolicyTag', - request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['create_policy_tag'] - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete policy tag method over gRPC. - - Deletes a policy tag together with the following: - - - All of its descendant policy tags, if any - - Policies associated with the policy tag and its descendants - - References from BigQuery table schema of the policy tag and - its descendants - - Returns: - Callable[[~.DeletePolicyTagRequest], - 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_policy_tag' not in self._stubs: - self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/DeletePolicyTag', - request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_policy_tag'] - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the update policy tag method over gRPC. - - Updates a policy tag, including its display - name, description, and parent policy tag. - - Returns: - Callable[[~.UpdatePolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/UpdatePolicyTag', - request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['update_policy_tag'] - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - Awaitable[policytagmanager.ListPolicyTagsResponse]]: - r"""Return a callable for the list policy tags method over gRPC. - - Lists all policy tags in a taxonomy. - - Returns: - Callable[[~.ListPolicyTagsRequest], - Awaitable[~.ListPolicyTagsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: - self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/ListPolicyTags', - request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, - response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, - ) - return self._stubs['list_policy_tags'] - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the get policy tag method over gRPC. - - Gets a policy tag. - - Returns: - Callable[[~.GetPolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetPolicyTag', - request_serializer=policytagmanager.GetPolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['get_policy_tag'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM policy for a policy tag or a taxonomy. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM policy for a policy tag or a taxonomy. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns your permissions on a specified policy tag or - taxonomy. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PolicyTagManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__init__.py deleted file mode 100644 index 5e73ed2a..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/__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 PolicyTagManagerSerializationClient -from .async_client import PolicyTagManagerSerializationAsyncClient - -__all__ = ( - 'PolicyTagManagerSerializationClient', - 'PolicyTagManagerSerializationAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py deleted file mode 100644 index 4ae79e6e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/async_client.py +++ /dev/null @@ -1,372 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization -from google.cloud.datacatalog_v1.types import timestamps -from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport -from .client import PolicyTagManagerSerializationClient - - -class PolicyTagManagerSerializationAsyncClient: - """Policy Tag Manager Serialization API service allows you to - manipulate your policy tags and taxonomies in a serialized - format. - Taxonomy is a hierarchical group of policy tags. - """ - - _client: PolicyTagManagerSerializationClient - - DEFAULT_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_MTLS_ENDPOINT - - taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.taxonomy_path) - parse_taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.parse_taxonomy_path) - common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PolicyTagManagerSerializationClient.common_folder_path) - parse_common_folder_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_folder_path) - common_organization_path = staticmethod(PolicyTagManagerSerializationClient.common_organization_path) - parse_common_organization_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_organization_path) - common_project_path = staticmethod(PolicyTagManagerSerializationClient.common_project_path) - parse_common_project_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_project_path) - common_location_path = staticmethod(PolicyTagManagerSerializationClient.common_location_path) - parse_common_location_path = staticmethod(PolicyTagManagerSerializationClient.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: - PolicyTagManagerSerializationAsyncClient: The constructed client. - """ - return PolicyTagManagerSerializationClient.from_service_account_info.__func__(PolicyTagManagerSerializationAsyncClient, 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: - PolicyTagManagerSerializationAsyncClient: The constructed client. - """ - return PolicyTagManagerSerializationClient.from_service_account_file.__func__(PolicyTagManagerSerializationAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PolicyTagManagerSerializationTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerSerializationTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PolicyTagManagerSerializationClient).get_transport_class, type(PolicyTagManagerSerializationClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PolicyTagManagerSerializationTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager serialization 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, ~.PolicyTagManagerSerializationTransport]): 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 = PolicyTagManagerSerializationClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def replace_taxonomy(self, - request: Union[policytagmanagerserialization.ReplaceTaxonomyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Replaces (updates) a taxonomy and all its policy tags. - - The taxonomy and its entire hierarchy of policy tags must be - represented literally by ``SerializedTaxonomy`` and the nested - ``SerializedPolicyTag`` messages. - - This operation automatically does the following: - - - Deletes the existing policy tags that are missing from the - ``SerializedPolicyTag``. - - Creates policy tags that don't have resource names. They are - considered new. - - Updates policy tags with valid resources names accordingly. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ReplaceTaxonomyRequest, dict]): - The request object. Request message for - [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # Create or coerce a protobuf request object. - request = policytagmanagerserialization.ReplaceTaxonomyRequest(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.replace_taxonomy, - default_timeout=None, - client_info=DEFAULT_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 import_taxonomies(self, - request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ImportTaxonomiesResponse: - r"""Creates new taxonomies (including their policy tags) - in a given project by importing from inlined or cross- - regional sources. - For a cross-regional source, new taxonomies are created - by copying from a source in another region. - - For an inlined source, taxonomies and policy tags are - created in bulk using nested protocol buffer structures. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ImportTaxonomiesRequest, dict]): - The request object. Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.ImportTaxonomiesResponse: - Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - request = policytagmanagerserialization.ImportTaxonomiesRequest(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.import_taxonomies, - default_timeout=None, - client_info=DEFAULT_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 export_taxonomies(self, - request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ExportTaxonomiesResponse: - r"""Exports taxonomies in the requested type and returns them, - including their policy tags. The requested taxonomies must - belong to the same project. - - This method generates ``SerializedTaxonomy`` protocol buffers - with nested policy tags that can be used as input for - ``ImportTaxonomies`` calls. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ExportTaxonomiesRequest, dict]): - The request object. Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.ExportTaxonomiesResponse: - Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - request = policytagmanagerserialization.ExportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_taxonomies, - default_timeout=None, - client_info=DEFAULT_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 __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerSerializationAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py deleted file mode 100644 index 898822f7..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py +++ /dev/null @@ -1,572 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization -from google.cloud.datacatalog_v1.types import timestamps -from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PolicyTagManagerSerializationGrpcTransport -from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport - - -class PolicyTagManagerSerializationClientMeta(type): - """Metaclass for the PolicyTagManagerSerialization 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[PolicyTagManagerSerializationTransport]] - _transport_registry["grpc"] = PolicyTagManagerSerializationGrpcTransport - _transport_registry["grpc_asyncio"] = PolicyTagManagerSerializationGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PolicyTagManagerSerializationTransport]: - """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 PolicyTagManagerSerializationClient(metaclass=PolicyTagManagerSerializationClientMeta): - """Policy Tag Manager Serialization API service allows you to - manipulate your policy tags and taxonomies in a serialized - format. - Taxonomy is a hierarchical group of policy tags. - """ - - @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 = "datacatalog.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: - PolicyTagManagerSerializationClient: 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: - PolicyTagManagerSerializationClient: 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) -> PolicyTagManagerSerializationTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerSerializationTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: - """Returns a fully-qualified taxonomy string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - - @staticmethod - def parse_taxonomy_path(path: str) -> Dict[str,str]: - """Parses a taxonomy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerSerializationTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager serialization 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, PolicyTagManagerSerializationTransport]): 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, PolicyTagManagerSerializationTransport): - # transport is a PolicyTagManagerSerializationTransport 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=True, - ) - - def replace_taxonomy(self, - request: Union[policytagmanagerserialization.ReplaceTaxonomyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Replaces (updates) a taxonomy and all its policy tags. - - The taxonomy and its entire hierarchy of policy tags must be - represented literally by ``SerializedTaxonomy`` and the nested - ``SerializedPolicyTag`` messages. - - This operation automatically does the following: - - - Deletes the existing policy tags that are missing from the - ``SerializedPolicyTag``. - - Creates policy tags that don't have resource names. They are - considered new. - - Updates policy tags with valid resources names accordingly. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ReplaceTaxonomyRequest, dict]): - The request object. Request message for - [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.Taxonomy: - A taxonomy is a collection of hierarchical policy tags that classify data - along a common axis. - - For example, a "data sensitivity" taxonomy might - contain the following policy tags: - - :literal:`\` + PII + Account number + Age + SSN + Zipcode + Financials + Revenue`\ \` - - A "data origin" taxonomy might contain the following - policy tags: - - :literal:`\` + User data + Employee data + Partner data + Public data`\ \` - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a policytagmanagerserialization.ReplaceTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanagerserialization.ReplaceTaxonomyRequest): - request = policytagmanagerserialization.ReplaceTaxonomyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_taxonomy] - - # Certain fields should be 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 import_taxonomies(self, - request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ImportTaxonomiesResponse: - r"""Creates new taxonomies (including their policy tags) - in a given project by importing from inlined or cross- - regional sources. - For a cross-regional source, new taxonomies are created - by copying from a source in another region. - - For an inlined source, taxonomies and policy tags are - created in bulk using nested protocol buffer structures. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ImportTaxonomiesRequest, dict]): - The request object. Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.ImportTaxonomiesResponse: - Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a policytagmanagerserialization.ImportTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanagerserialization.ImportTaxonomiesRequest): - request = policytagmanagerserialization.ImportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_taxonomies] - - # 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 export_taxonomies(self, - request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ExportTaxonomiesResponse: - r"""Exports taxonomies in the requested type and returns them, - including their policy tags. The requested taxonomies must - belong to the same project. - - This method generates ``SerializedTaxonomy`` protocol buffers - with nested policy tags that can be used as input for - ``ImportTaxonomies`` calls. - - Args: - request (Union[google.cloud.datacatalog_v1.types.ExportTaxonomiesRequest, dict]): - The request object. Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1.types.ExportTaxonomiesResponse: - Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a policytagmanagerserialization.ExportTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanagerserialization.ExportTaxonomiesRequest): - request = policytagmanagerserialization.ExportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_taxonomies] - - # 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 __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerSerializationClient", -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/__init__.py deleted file mode 100644 index 2864dab0..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/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 PolicyTagManagerSerializationTransport -from .grpc import PolicyTagManagerSerializationGrpcTransport -from .grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerSerializationTransport]] -_transport_registry['grpc'] = PolicyTagManagerSerializationGrpcTransport -_transport_registry['grpc_asyncio'] = PolicyTagManagerSerializationGrpcAsyncIOTransport - -__all__ = ( - 'PolicyTagManagerSerializationTransport', - 'PolicyTagManagerSerializationGrpcTransport', - 'PolicyTagManagerSerializationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py deleted file mode 100644 index 2bf138ba..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/base.py +++ /dev/null @@ -1,175 +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 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.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PolicyTagManagerSerializationTransport(abc.ABC): - """Abstract transport class for PolicyTagManagerSerialization.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.replace_taxonomy: gapic_v1.method.wrap_method( - self.replace_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.import_taxonomies: gapic_v1.method.wrap_method( - self.import_taxonomies, - default_timeout=None, - client_info=client_info, - ), - self.export_taxonomies: gapic_v1.method.wrap_method( - self.export_taxonomies, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def replace_taxonomy(self) -> Callable[ - [policytagmanagerserialization.ReplaceTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - Union[ - policytagmanagerserialization.ImportTaxonomiesResponse, - Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse] - ]]: - raise NotImplementedError() - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - Union[ - policytagmanagerserialization.ExportTaxonomiesResponse, - Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PolicyTagManagerSerializationTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py deleted file mode 100644 index 5255af94..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc.py +++ /dev/null @@ -1,335 +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.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization -from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO - - -class PolicyTagManagerSerializationGrpcTransport(PolicyTagManagerSerializationTransport): - """gRPC backend transport for PolicyTagManagerSerialization. - - Policy Tag Manager Serialization API service allows you to - manipulate your policy tags and taxonomies in a serialized - format. - Taxonomy is a hierarchical group of policy tags. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 replace_taxonomy(self) -> Callable[ - [policytagmanagerserialization.ReplaceTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the replace taxonomy method over gRPC. - - Replaces (updates) a taxonomy and all its policy tags. - - The taxonomy and its entire hierarchy of policy tags must be - represented literally by ``SerializedTaxonomy`` and the nested - ``SerializedPolicyTag`` messages. - - This operation automatically does the following: - - - Deletes the existing policy tags that are missing from the - ``SerializedPolicyTag``. - - Creates policy tags that don't have resource names. They are - considered new. - - Updates policy tags with valid resources names accordingly. - - Returns: - Callable[[~.ReplaceTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_taxonomy' not in self._stubs: - self._stubs['replace_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ReplaceTaxonomy', - request_serializer=policytagmanagerserialization.ReplaceTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['replace_taxonomy'] - - @property - def import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - policytagmanagerserialization.ImportTaxonomiesResponse]: - r"""Return a callable for the import taxonomies method over gRPC. - - Creates new taxonomies (including their policy tags) - in a given project by importing from inlined or cross- - regional sources. - For a cross-regional source, new taxonomies are created - by copying from a source in another region. - - For an inlined source, taxonomies and policy tags are - created in bulk using nested protocol buffer structures. - - Returns: - Callable[[~.ImportTaxonomiesRequest], - ~.ImportTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_taxonomies' not in self._stubs: - self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ImportTaxonomies', - request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, - ) - return self._stubs['import_taxonomies'] - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - policytagmanagerserialization.ExportTaxonomiesResponse]: - r"""Return a callable for the export taxonomies method over gRPC. - - Exports taxonomies in the requested type and returns them, - including their policy tags. The requested taxonomies must - belong to the same project. - - This method generates ``SerializedTaxonomy`` protocol buffers - with nested policy tags that can be used as input for - ``ImportTaxonomies`` calls. - - Returns: - Callable[[~.ExportTaxonomiesRequest], - ~.ExportTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_taxonomies' not in self._stubs: - self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ExportTaxonomies', - request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, - ) - return self._stubs['export_taxonomies'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'PolicyTagManagerSerializationGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py deleted file mode 100644 index 3291686e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py +++ /dev/null @@ -1,339 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization -from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .grpc import PolicyTagManagerSerializationGrpcTransport - - -class PolicyTagManagerSerializationGrpcAsyncIOTransport(PolicyTagManagerSerializationTransport): - """gRPC AsyncIO backend transport for PolicyTagManagerSerialization. - - Policy Tag Manager Serialization API service allows you to - manipulate your policy tags and taxonomies in a serialized - format. - Taxonomy is a hierarchical group of policy tags. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 replace_taxonomy(self) -> Callable[ - [policytagmanagerserialization.ReplaceTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the replace taxonomy method over gRPC. - - Replaces (updates) a taxonomy and all its policy tags. - - The taxonomy and its entire hierarchy of policy tags must be - represented literally by ``SerializedTaxonomy`` and the nested - ``SerializedPolicyTag`` messages. - - This operation automatically does the following: - - - Deletes the existing policy tags that are missing from the - ``SerializedPolicyTag``. - - Creates policy tags that don't have resource names. They are - considered new. - - Updates policy tags with valid resources names accordingly. - - Returns: - Callable[[~.ReplaceTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'replace_taxonomy' not in self._stubs: - self._stubs['replace_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ReplaceTaxonomy', - request_serializer=policytagmanagerserialization.ReplaceTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['replace_taxonomy'] - - @property - def import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse]]: - r"""Return a callable for the import taxonomies method over gRPC. - - Creates new taxonomies (including their policy tags) - in a given project by importing from inlined or cross- - regional sources. - For a cross-regional source, new taxonomies are created - by copying from a source in another region. - - For an inlined source, taxonomies and policy tags are - created in bulk using nested protocol buffer structures. - - Returns: - Callable[[~.ImportTaxonomiesRequest], - Awaitable[~.ImportTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_taxonomies' not in self._stubs: - self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ImportTaxonomies', - request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, - ) - return self._stubs['import_taxonomies'] - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse]]: - r"""Return a callable for the export taxonomies method over gRPC. - - Exports taxonomies in the requested type and returns them, - including their policy tags. The requested taxonomies must - belong to the same project. - - This method generates ``SerializedTaxonomy`` protocol buffers - with nested policy tags that can be used as input for - ``ImportTaxonomies`` calls. - - Returns: - Callable[[~.ExportTaxonomiesRequest], - Awaitable[~.ExportTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_taxonomies' not in self._stubs: - self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1.PolicyTagManagerSerialization/ExportTaxonomies', - request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, - ) - return self._stubs['export_taxonomies'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PolicyTagManagerSerializationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py deleted file mode 100644 index d9d6c548..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/__init__.py +++ /dev/null @@ -1,205 +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 .bigquery import ( - BigQueryConnectionSpec, - BigQueryRoutineSpec, - CloudSqlBigQueryConnectionSpec, -) -from .data_source import ( - DataSource, -) -from .datacatalog import ( - CreateEntryGroupRequest, - CreateEntryRequest, - CreateTagRequest, - CreateTagTemplateFieldRequest, - CreateTagTemplateRequest, - DatabaseTableSpec, - DataSourceConnectionSpec, - DeleteEntryGroupRequest, - DeleteEntryRequest, - DeleteTagRequest, - DeleteTagTemplateFieldRequest, - DeleteTagTemplateRequest, - Entry, - EntryGroup, - GetEntryGroupRequest, - GetEntryRequest, - GetTagTemplateRequest, - ListEntriesRequest, - ListEntriesResponse, - ListEntryGroupsRequest, - ListEntryGroupsResponse, - ListTagsRequest, - ListTagsResponse, - LookupEntryRequest, - RenameTagTemplateFieldEnumValueRequest, - RenameTagTemplateFieldRequest, - RoutineSpec, - SearchCatalogRequest, - SearchCatalogResponse, - UpdateEntryGroupRequest, - UpdateEntryRequest, - UpdateTagRequest, - UpdateTagTemplateFieldRequest, - UpdateTagTemplateRequest, - EntryType, -) -from .gcs_fileset_spec import ( - GcsFilesetSpec, - GcsFileSpec, -) -from .policytagmanager import ( - CreatePolicyTagRequest, - CreateTaxonomyRequest, - DeletePolicyTagRequest, - DeleteTaxonomyRequest, - GetPolicyTagRequest, - GetTaxonomyRequest, - ListPolicyTagsRequest, - ListPolicyTagsResponse, - ListTaxonomiesRequest, - ListTaxonomiesResponse, - PolicyTag, - Taxonomy, - UpdatePolicyTagRequest, - UpdateTaxonomyRequest, -) -from .policytagmanagerserialization import ( - CrossRegionalSource, - ExportTaxonomiesRequest, - ExportTaxonomiesResponse, - ImportTaxonomiesRequest, - ImportTaxonomiesResponse, - InlineSource, - ReplaceTaxonomyRequest, - SerializedPolicyTag, - SerializedTaxonomy, -) -from .schema import ( - ColumnSchema, - Schema, -) -from .search import ( - SearchCatalogResult, - SearchResultType, -) -from .table_spec import ( - BigQueryDateShardedSpec, - BigQueryTableSpec, - TableSpec, - ViewSpec, - TableSourceType, -) -from .tags import ( - FieldType, - Tag, - TagField, - TagTemplate, - TagTemplateField, -) -from .timestamps import ( - SystemTimestamps, -) -from .usage import ( - UsageSignal, - UsageStats, -) - -__all__ = ( - 'BigQueryConnectionSpec', - 'BigQueryRoutineSpec', - 'CloudSqlBigQueryConnectionSpec', - 'IntegratedSystem', - 'DataSource', - 'CreateEntryGroupRequest', - 'CreateEntryRequest', - 'CreateTagRequest', - 'CreateTagTemplateFieldRequest', - 'CreateTagTemplateRequest', - 'DatabaseTableSpec', - 'DataSourceConnectionSpec', - 'DeleteEntryGroupRequest', - 'DeleteEntryRequest', - 'DeleteTagRequest', - 'DeleteTagTemplateFieldRequest', - 'DeleteTagTemplateRequest', - 'Entry', - 'EntryGroup', - 'GetEntryGroupRequest', - 'GetEntryRequest', - 'GetTagTemplateRequest', - 'ListEntriesRequest', - 'ListEntriesResponse', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'ListTagsRequest', - 'ListTagsResponse', - 'LookupEntryRequest', - 'RenameTagTemplateFieldEnumValueRequest', - 'RenameTagTemplateFieldRequest', - 'RoutineSpec', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'UpdateEntryGroupRequest', - 'UpdateEntryRequest', - 'UpdateTagRequest', - 'UpdateTagTemplateFieldRequest', - 'UpdateTagTemplateRequest', - 'EntryType', - 'GcsFilesetSpec', - 'GcsFileSpec', - 'CreatePolicyTagRequest', - 'CreateTaxonomyRequest', - 'DeletePolicyTagRequest', - 'DeleteTaxonomyRequest', - 'GetPolicyTagRequest', - 'GetTaxonomyRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'PolicyTag', - 'Taxonomy', - 'UpdatePolicyTagRequest', - 'UpdateTaxonomyRequest', - 'CrossRegionalSource', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - 'ImportTaxonomiesRequest', - 'ImportTaxonomiesResponse', - 'InlineSource', - 'ReplaceTaxonomyRequest', - 'SerializedPolicyTag', - 'SerializedTaxonomy', - 'ColumnSchema', - 'Schema', - 'SearchCatalogResult', - 'SearchResultType', - 'BigQueryDateShardedSpec', - 'BigQueryTableSpec', - 'TableSpec', - 'ViewSpec', - 'TableSourceType', - 'FieldType', - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'SystemTimestamps', - 'UsageSignal', - 'UsageStats', -) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py deleted file mode 100644 index ab7ba45a..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/bigquery.py +++ /dev/null @@ -1,115 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'BigQueryConnectionSpec', - 'CloudSqlBigQueryConnectionSpec', - 'BigQueryRoutineSpec', - }, -) - - -class BigQueryConnectionSpec(proto.Message): - r"""Specification for the BigQuery connection. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - connection_type (google.cloud.datacatalog_v1.types.BigQueryConnectionSpec.ConnectionType): - The type of the BigQuery connection. - cloud_sql (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec): - Specification for the BigQuery connection to - a Cloud SQL instance. - This field is a member of `oneof`_ ``connection_spec``. - has_credential (bool): - True if there are credentials attached to the - BigQuery connection; false otherwise. - """ - class ConnectionType(proto.Enum): - r"""The type of the BigQuery connection.""" - CONNECTION_TYPE_UNSPECIFIED = 0 - CLOUD_SQL = 1 - - connection_type = proto.Field( - proto.ENUM, - number=1, - enum=ConnectionType, - ) - cloud_sql = proto.Field( - proto.MESSAGE, - number=2, - oneof='connection_spec', - message='CloudSqlBigQueryConnectionSpec', - ) - has_credential = proto.Field( - proto.BOOL, - number=3, - ) - - -class CloudSqlBigQueryConnectionSpec(proto.Message): - r"""Specification for the BigQuery connection to a Cloud SQL - instance. - - Attributes: - instance_id (str): - Cloud SQL instance ID in the format of - ``project:location:instance``. - database (str): - Database name. - type_ (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec.DatabaseType): - Type of the Cloud SQL database. - """ - class DatabaseType(proto.Enum): - r"""Supported Cloud SQL database types.""" - DATABASE_TYPE_UNSPECIFIED = 0 - POSTGRES = 1 - MYSQL = 2 - - instance_id = proto.Field( - proto.STRING, - number=1, - ) - database = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=DatabaseType, - ) - - -class BigQueryRoutineSpec(proto.Message): - r"""Fields specific for BigQuery routines. - - Attributes: - imported_libraries (Sequence[str]): - Paths of the imported libraries. - """ - - imported_libraries = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py deleted file mode 100644 index 60d41442..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/common.py +++ /dev/null @@ -1,37 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'IntegratedSystem', - }, -) - - -class IntegratedSystem(proto.Enum): - r"""This enum lists all the systems that Data Catalog integrates - with. - """ - INTEGRATED_SYSTEM_UNSPECIFIED = 0 - BIGQUERY = 1 - CLOUD_PUBSUB = 2 - DATAPROC_METASTORE = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py deleted file mode 100644 index 2506054d..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/data_source.py +++ /dev/null @@ -1,56 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'DataSource', - }, -) - - -class DataSource(proto.Message): - r"""Physical location of an entry. - - Attributes: - service (google.cloud.datacatalog_v1.types.DataSource.Service): - Service that physically stores the data. - resource (str): - Full name of a resource as defined by the service. For - example: - - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/locations/{LOCATION}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` - """ - class Service(proto.Enum): - r"""Name of a service that stores the data.""" - SERVICE_UNSPECIFIED = 0 - CLOUD_STORAGE = 1 - BIGQUERY = 2 - - service = proto.Field( - proto.ENUM, - number=1, - enum=Service, - ) - resource = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py deleted file mode 100644 index 8fb5604a..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/datacatalog.py +++ /dev/null @@ -1,1578 +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.datacatalog_v1.types import bigquery -from google.cloud.datacatalog_v1.types import common -from google.cloud.datacatalog_v1.types import data_source as gcd_data_source -from google.cloud.datacatalog_v1.types import gcs_fileset_spec as gcd_gcs_fileset_spec -from google.cloud.datacatalog_v1.types import schema as gcd_schema -from google.cloud.datacatalog_v1.types import search -from google.cloud.datacatalog_v1.types import table_spec -from google.cloud.datacatalog_v1.types import tags as gcd_tags -from google.cloud.datacatalog_v1.types import timestamps -from google.cloud.datacatalog_v1.types import usage -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'EntryType', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'CreateEntryGroupRequest', - 'UpdateEntryGroupRequest', - 'GetEntryGroupRequest', - 'DeleteEntryGroupRequest', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'CreateEntryRequest', - 'UpdateEntryRequest', - 'DeleteEntryRequest', - 'GetEntryRequest', - 'LookupEntryRequest', - 'Entry', - 'DatabaseTableSpec', - 'DataSourceConnectionSpec', - 'RoutineSpec', - 'EntryGroup', - 'CreateTagTemplateRequest', - 'GetTagTemplateRequest', - 'UpdateTagTemplateRequest', - 'DeleteTagTemplateRequest', - 'CreateTagRequest', - 'UpdateTagRequest', - 'DeleteTagRequest', - 'CreateTagTemplateFieldRequest', - 'UpdateTagTemplateFieldRequest', - 'RenameTagTemplateFieldRequest', - 'RenameTagTemplateFieldEnumValueRequest', - 'DeleteTagTemplateFieldRequest', - 'ListTagsRequest', - 'ListTagsResponse', - 'ListEntriesRequest', - 'ListEntriesResponse', - }, -) - - -class EntryType(proto.Enum): - r"""The enum field that lists all the types of entry resources in Data - Catalog. For example, a BigQuery table entry has the ``TABLE`` type. - """ - ENTRY_TYPE_UNSPECIFIED = 0 - TABLE = 2 - MODEL = 5 - DATA_STREAM = 3 - FILESET = 4 - CLUSTER = 6 - DATABASE = 7 - DATA_SOURCE_CONNECTION = 8 - ROUTINE = 9 - SERVICE = 14 - - -class SearchCatalogRequest(proto.Message): - r"""Request message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Attributes: - scope (google.cloud.datacatalog_v1.types.SearchCatalogRequest.Scope): - Required. The scope of this search request. - - The ``scope`` is invalid if ``include_org_ids``, - ``include_project_ids`` are empty AND - ``include_gcp_public_datasets`` is set to ``false``. In this - case, the request returns an error. - query (str): - Optional. The query string with a minimum of 3 characters - and specific syntax. For more information, see `Data Catalog - search - syntax `__. - - An empty query string returns all data assets (in the - specified scope) that you have access to. - - A query string can be a simple ``xyz`` or qualified by - predicates: - - - ``name:x`` - - ``column:y`` - - ``description:z`` - page_size (int): - Number of results to return in a single - search page. - Can't be negative or 0, defaults to 10 in this - case. The maximum number is 1000. If exceeded, - throws an "invalid argument" exception. - page_token (str): - Optional. Pagination token that, if specified, returns the - next page of search results. If empty, returns the first - page. - - This token is returned in the - [SearchCatalogResponse.next_page_token][google.cloud.datacatalog.v1.SearchCatalogResponse.next_page_token] - field of the response to a previous - [SearchCatalogRequest][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog] - call. - order_by (str): - Specifies the order of results. - - Currently supported case-sensitive values are: - - - ``relevance`` that can only be descending - - ``last_modified_timestamp [asc|desc]`` with descending - (``desc``) as default - - If this parameter is omitted, it defaults to the descending - ``relevance``. - """ - - class Scope(proto.Message): - r"""The criteria that select the subspace used for query - matching. - - Attributes: - include_org_ids (Sequence[str]): - The list of organization IDs to search within. - - To find your organization ID, follow the steps from - [Creating and managing organizations] - (/resource-manager/docs/creating-managing-organization). - include_project_ids (Sequence[str]): - The list of project IDs to search within. - - For more information on the distinction between project - names, IDs, and numbers, see - `Projects `__. - include_gcp_public_datasets (bool): - If ``true``, include Google Cloud Platform (GCP) public - datasets in search results. By default, they are excluded. - - See `Google Cloud Public Datasets `__ for - more information. - restricted_locations (Sequence[str]): - Optional. The list of locations to search within. If empty, - all locations are searched. - - Returns an error if any location in the list isn't one of - the `Supported - regions `__. - - If a location is unreachable, its name is returned in the - ``SearchCatalogResponse.unreachable`` field. To get - additional information on the error, repeat the search - request and set the location name as the value of this - parameter. - include_public_tag_templates (bool): - Optional. If ``true``, include [public tag - templates][google.cloud.datacatalog.v1.TagTemplate.is_publicly_readable] - in the search results. By default, they are included only if - you have explicit permissions on them to view them. For - example, if you are the owner. - - Other scope fields, for example, ``include_org_ids``, still - restrict the returned public tag templates and at least one - of them is required. - """ - - include_org_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - include_project_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - include_gcp_public_datasets = proto.Field( - proto.BOOL, - number=7, - ) - restricted_locations = proto.RepeatedField( - proto.STRING, - number=16, - ) - include_public_tag_templates = proto.Field( - proto.BOOL, - number=19, - ) - - scope = proto.Field( - proto.MESSAGE, - number=6, - message=Scope, - ) - query = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class SearchCatalogResponse(proto.Message): - r"""Response message for - [SearchCatalog][google.cloud.datacatalog.v1.DataCatalog.SearchCatalog]. - - Attributes: - results (Sequence[google.cloud.datacatalog_v1.types.SearchCatalogResult]): - Search results. - next_page_token (str): - Pagination token that can be used in - subsequent calls to retrieve the next page of - results. - unreachable (Sequence[str]): - Unreachable locations. Search results don't include data - from those locations. - - To get additional information on an error, repeat the search - request and restrict it to specific locations by setting the - ``SearchCatalogRequest.scope.restricted_locations`` - parameter. - """ - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=search.SearchCatalogResult, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - unreachable = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class CreateEntryGroupRequest(proto.Message): - r"""Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.CreateEntryGroup]. - - Attributes: - parent (str): - Required. The names of the project and - location that the new entry group belongs to. - Note: The entry group itself and its child - resources might not be stored in the location - specified in its name. - entry_group_id (str): - Required. The ID of the entry group to create. - - The ID must contain only letters (a-z, A-Z), numbers (0-9), - underscores (_), and must start with a letter or underscore. - The maximum size is 64 bytes when encoded in UTF-8. - entry_group (google.cloud.datacatalog_v1.types.EntryGroup): - The entry group to create. Defaults to empty. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entry_group_id = proto.Field( - proto.STRING, - number=3, - ) - entry_group = proto.Field( - proto.MESSAGE, - number=2, - message='EntryGroup', - ) - - -class UpdateEntryGroupRequest(proto.Message): - r"""Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1.DataCatalog.UpdateEntryGroup]. - - Attributes: - entry_group (google.cloud.datacatalog_v1.types.EntryGroup): - Required. Updates for the entry group. The ``name`` field - must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on - an entry group. - If this parameter is absent or empty, all - modifiable fields are overwritten. If such - fields are non-required and omitted in the - request body, their values are emptied. - """ - - entry_group = proto.Field( - proto.MESSAGE, - number=1, - message='EntryGroup', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEntryGroupRequest(proto.Message): - r"""Request message for - [GetEntryGroup][google.cloud.datacatalog.v1.DataCatalog.GetEntryGroup]. - - Attributes: - name (str): - Required. The name of the entry group to get. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return. If empty or omitted, - all fields are returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntryGroupRequest(proto.Message): - r"""Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1.DataCatalog.DeleteEntryGroup]. - - Attributes: - name (str): - Required. The name of the entry group to - delete. - force (bool): - Optional. If true, deletes all entries in the - entry group. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListEntryGroupsRequest(proto.Message): - r"""Request message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - - Attributes: - parent (str): - Required. The name of the location that - contains the entry groups to list. - Can be provided as a URL. - page_size (int): - Optional. The maximum number of items to return. - - Default is 10. Maximum limit is 1000. Throws an invalid - argument if ``page_size`` is greater than 1000. - page_token (str): - Optional. Pagination token that specifies the - next page to return. If empty, returns the first - page. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEntryGroupsResponse(proto.Message): - r"""Response message for - [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups]. - - Attributes: - entry_groups (Sequence[google.cloud.datacatalog_v1.types.EntryGroup]): - Entry group details. - next_page_token (str): - Pagination token to specify in the next call - to retrieve the next page of results. Empty if - there are no more items. - """ - - @property - def raw_page(self): - return self - - entry_groups = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntryGroup', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateEntryRequest(proto.Message): - r"""Request message for - [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry]. - - Attributes: - parent (str): - Required. The name of the entry group this - entry belongs to. - Note: The entry itself and its child resources - might not be stored in the location specified in - its name. - entry_id (str): - Required. The ID of the entry to create. - - The ID must contain only letters (a-z, A-Z), numbers (0-9), - and underscores (_). The maximum size is 64 bytes when - encoded in UTF-8. - entry (google.cloud.datacatalog_v1.types.Entry): - Required. The entry to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entry_id = proto.Field( - proto.STRING, - number=3, - ) - entry = proto.Field( - proto.MESSAGE, - number=2, - message='Entry', - ) - - -class UpdateEntryRequest(proto.Message): - r"""Request message for - [UpdateEntry][google.cloud.datacatalog.v1.DataCatalog.UpdateEntry]. - - Attributes: - entry (google.cloud.datacatalog_v1.types.Entry): - Required. Updates for the entry. The ``name`` field must be - set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on an entry. - - If this parameter is absent or empty, all modifiable fields - are overwritten. If such fields are non-required and omitted - in the request body, their values are emptied. - - You can modify only the fields listed below. - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - For entries with type ``FILESET``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - For entries with ``user_specified_type``: - - - ``schema`` - - ``display_name`` - - ``description`` - - ``user_specified_type`` - - ``user_specified_system`` - - ``linked_resource`` - - ``source_system_timestamps`` - """ - - entry = proto.Field( - proto.MESSAGE, - number=1, - message='Entry', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntryRequest(proto.Message): - r"""Request message for - [DeleteEntry][google.cloud.datacatalog.v1.DataCatalog.DeleteEntry]. - - Attributes: - name (str): - Required. The name of the entry to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEntryRequest(proto.Message): - r"""Request message for - [GetEntry][google.cloud.datacatalog.v1.DataCatalog.GetEntry]. - - Attributes: - name (str): - Required. The name of the entry to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LookupEntryRequest(proto.Message): - r"""Request message for - [LookupEntry][google.cloud.datacatalog.v1.DataCatalog.LookupEntry]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - linked_resource (str): - The full name of the Google Cloud Platform resource the Data - Catalog entry represents. For more information, see [Full - Resource Name] - (https://cloud.google.com/apis/design/resource_names#full_resource_name). - - Full names are case-sensitive. For example: - - - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` - - ``//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}`` - This field is a member of `oneof`_ ``target_name``. - sql_resource (str): - The SQL name of the entry. SQL names are case-sensitive. - - Examples: - - - ``pubsub.topic.{PROJECT_ID}.{TOPIC_ID}`` - - ``pubsub.topic.{PROJECT_ID}.``\ \`\ ``{TOPIC.ID.SEPARATED.WITH.DOTS}``\ \` - - ``bigquery.table.{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}`` - - ``bigquery.dataset.{PROJECT_ID}.{DATASET_ID}`` - - ``datacatalog.entry.{PROJECT_ID}.{LOCATION_ID}.{ENTRY_GROUP_ID}.{ENTRY_ID}`` - - Identifiers (``*_ID``) should comply with the [Lexical - structure in Standard SQL] - (https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical). - This field is a member of `oneof`_ ``target_name``. - fully_qualified_name (str): - Fully qualified name (FQN) of the resource. - - FQNs take two forms: - - - For non-regionalized resources: - - ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - - For regionalized resources: - - ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - Example for a DPMS table: - - ``dataproc_metastore:{PROJECT_ID}.{LOCATION_ID}.{INSTANCE_ID}.{DATABASE_ID}.{TABLE_ID}`` - This field is a member of `oneof`_ ``target_name``. - """ - - linked_resource = proto.Field( - proto.STRING, - number=1, - oneof='target_name', - ) - sql_resource = proto.Field( - proto.STRING, - number=3, - oneof='target_name', - ) - fully_qualified_name = proto.Field( - proto.STRING, - number=5, - oneof='target_name', - ) - - -class Entry(proto.Message): - r"""Entry metadata. A Data Catalog entry represents another resource in - Google Cloud Platform (such as a BigQuery dataset or a Pub/Sub - topic) or outside of it. You can use the ``linked_resource`` field - in the entry resource to refer to the original resource ID of the - source system. - - An entry resource contains resource details, for example, its - schema. Additionally, you can attach flexible metadata to an entry - in the form of a [Tag][google.cloud.datacatalog.v1.Tag]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The resource name of an entry in - URL format. - Note: The entry itself and its child resources - might not be stored in the location specified in - its name. - linked_resource (str): - The resource this metadata entry refers to. - - For Google Cloud Platform resources, ``linked_resource`` is - the [Full Resource Name] - (https://cloud.google.com/apis/design/resource_names#full_resource_name). - For example, the ``linked_resource`` for a table resource - from BigQuery is: - - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` - - Output only when the entry is one of the types in the - ``EntryType`` enum. - - For entries with a ``user_specified_type``, this field is - optional and defaults to an empty string. - - The resource string must contain only letters (a-z, A-Z), - numbers (0-9), underscores (_), periods (.), colons (:), - slashes (/), dashes (-), and hashes (#). The maximum size is - 200 bytes when encoded in UTF-8. - fully_qualified_name (str): - Fully qualified name (FQN) of the resource. Set - automatically for entries representing resources from synced - systems. Settable only during creation and read-only - afterwards. Can be used for search and lookup of the - entries. - - FQNs take two forms: - - - For non-regionalized resources: - - ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - - For regionalized resources: - - ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - Example for a DPMS table: - - ``dataproc_metastore:{PROJECT_ID}.{LOCATION_ID}.{INSTANCE_ID}.{DATABASE_ID}.{TABLE_ID}`` - type_ (google.cloud.datacatalog_v1.types.EntryType): - The type of the entry. Only used for entries with types - listed in the ``EntryType`` enum. - - Currently, only ``FILESET`` enum value is allowed. All other - entries created in Data Catalog must use the - ``user_specified_type``. - This field is a member of `oneof`_ ``entry_type``. - user_specified_type (str): - Custom entry type that doesn't match any of the values - allowed for input and listed in the ``EntryType`` enum. - - When creating an entry, first check the type values in the - enum. If there are no appropriate types for the new entry, - provide a custom value, for example, ``my_special_type``. - - The ``user_specified_type`` string has the following - limitations: - - - Is case insensitive. - - Must begin with a letter or underscore. - - Can only contain letters, numbers, and underscores. - - Must be at least 1 character and at most 64 characters - long. - This field is a member of `oneof`_ ``entry_type``. - integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): - Output only. Indicates the entry's source - system that Data Catalog integrates with, such - as BigQuery, Pub/Sub, or Dataproc Metastore. - This field is a member of `oneof`_ ``system``. - user_specified_system (str): - Indicates the entry's source system that Data Catalog - doesn't automatically integrate with. - - The ``user_specified_system`` string has the following - limitations: - - - Is case insensitive. - - Must begin with a letter or underscore. - - Can only contain letters, numbers, and underscores. - - Must be at least 1 character and at most 64 characters - long. - This field is a member of `oneof`_ ``system``. - gcs_fileset_spec (google.cloud.datacatalog_v1.types.GcsFilesetSpec): - Specification that applies to a Cloud Storage fileset. Valid - only for entries with the ``FILESET`` type. - This field is a member of `oneof`_ ``type_spec``. - bigquery_table_spec (google.cloud.datacatalog_v1.types.BigQueryTableSpec): - Specification that applies to a BigQuery table. Valid only - for entries with the ``TABLE`` type. - This field is a member of `oneof`_ ``type_spec``. - bigquery_date_sharded_spec (google.cloud.datacatalog_v1.types.BigQueryDateShardedSpec): - Specification for a group of BigQuery tables with the - ``[prefix]YYYYMMDD`` name pattern. - - For more information, see [Introduction to partitioned - tables] - (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). - This field is a member of `oneof`_ ``type_spec``. - database_table_spec (google.cloud.datacatalog_v1.types.DatabaseTableSpec): - Specification that applies to a table resource. Valid only - for entries with the ``TABLE`` type. - This field is a member of `oneof`_ ``spec``. - data_source_connection_spec (google.cloud.datacatalog_v1.types.DataSourceConnectionSpec): - Specification that applies to a data source connection. - Valid only for entries with the ``DATA_SOURCE_CONNECTION`` - type. - This field is a member of `oneof`_ ``spec``. - routine_spec (google.cloud.datacatalog_v1.types.RoutineSpec): - Specification that applies to a user-defined function or - procedure. Valid only for entries with the ``ROUTINE`` type. - This field is a member of `oneof`_ ``spec``. - display_name (str): - Display name of an entry. - - The name must contain only Unicode letters, numbers (0-9), - underscores (_), dashes (-), spaces ( ), and can't start or - end with spaces. The maximum size is 200 bytes when encoded - in UTF-8. Default value is an empty string. - description (str): - Entry description that can consist of several - sentences or paragraphs that describe entry - contents. - The description must not contain Unicode non- - characters as well as C0 and C1 control codes - except tabs (HT), new lines (LF), carriage - returns (CR), and page breaks (FF). - The maximum size is 2000 bytes when encoded in - UTF-8. Default value is an empty string. - schema (google.cloud.datacatalog_v1.types.Schema): - Schema of the entry. An entry might not have - any schema attached to it. - source_system_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): - Timestamps from the underlying resource, not from the Data - Catalog entry. - - Output only when the entry has a type listed in the - ``EntryType`` enum. For entries with - ``user_specified_type``, this field is optional and defaults - to an empty timestamp. - usage_signal (google.cloud.datacatalog_v1.types.UsageSignal): - Output only. Resource usage statistics. - labels (Sequence[google.cloud.datacatalog_v1.types.Entry.LabelsEntry]): - Cloud labels attached to the entry. - In Data Catalog, you can create and modify - labels attached only to custom entries. Synced - entries have unmodifiable labels that come from - the source system. - data_source (google.cloud.datacatalog_v1.types.DataSource): - Output only. Physical location of the entry. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - linked_resource = proto.Field( - proto.STRING, - number=9, - ) - fully_qualified_name = proto.Field( - proto.STRING, - number=29, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - oneof='entry_type', - enum='EntryType', - ) - user_specified_type = proto.Field( - proto.STRING, - number=16, - oneof='entry_type', - ) - integrated_system = proto.Field( - proto.ENUM, - number=17, - oneof='system', - enum=common.IntegratedSystem, - ) - user_specified_system = proto.Field( - proto.STRING, - number=18, - oneof='system', - ) - gcs_fileset_spec = proto.Field( - proto.MESSAGE, - number=6, - oneof='type_spec', - message=gcd_gcs_fileset_spec.GcsFilesetSpec, - ) - bigquery_table_spec = proto.Field( - proto.MESSAGE, - number=12, - oneof='type_spec', - message=table_spec.BigQueryTableSpec, - ) - bigquery_date_sharded_spec = proto.Field( - proto.MESSAGE, - number=15, - oneof='type_spec', - message=table_spec.BigQueryDateShardedSpec, - ) - database_table_spec = proto.Field( - proto.MESSAGE, - number=24, - oneof='spec', - message='DatabaseTableSpec', - ) - data_source_connection_spec = proto.Field( - proto.MESSAGE, - number=27, - oneof='spec', - message='DataSourceConnectionSpec', - ) - routine_spec = proto.Field( - proto.MESSAGE, - number=28, - oneof='spec', - message='RoutineSpec', - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - schema = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_schema.Schema, - ) - source_system_timestamps = proto.Field( - proto.MESSAGE, - number=7, - message=timestamps.SystemTimestamps, - ) - usage_signal = proto.Field( - proto.MESSAGE, - number=13, - message=usage.UsageSignal, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - data_source = proto.Field( - proto.MESSAGE, - number=20, - message=gcd_data_source.DataSource, - ) - - -class DatabaseTableSpec(proto.Message): - r"""Specification that applies to a table resource. Valid only for - entries with the ``TABLE`` type. - - Attributes: - type_ (google.cloud.datacatalog_v1.types.DatabaseTableSpec.TableType): - Type of this table. - """ - class TableType(proto.Enum): - r"""Type of the table.""" - TABLE_TYPE_UNSPECIFIED = 0 - NATIVE = 1 - EXTERNAL = 2 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=TableType, - ) - - -class DataSourceConnectionSpec(proto.Message): - r"""Specification that applies to a data source connection. Valid only - for entries with the ``DATA_SOURCE_CONNECTION`` type. - - Attributes: - bigquery_connection_spec (google.cloud.datacatalog_v1.types.BigQueryConnectionSpec): - Fields specific to BigQuery connections. - """ - - bigquery_connection_spec = proto.Field( - proto.MESSAGE, - number=1, - message=bigquery.BigQueryConnectionSpec, - ) - - -class RoutineSpec(proto.Message): - r"""Specification that applies to a routine. Valid only for entries with - the ``ROUTINE`` type. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - routine_type (google.cloud.datacatalog_v1.types.RoutineSpec.RoutineType): - The type of the routine. - language (str): - The language the routine is written in. The exact value - depends on the source system. For BigQuery routines, - possible values are: - - - ``SQL`` - - ``JAVASCRIPT`` - routine_arguments (Sequence[google.cloud.datacatalog_v1.types.RoutineSpec.Argument]): - Arguments of the routine. - return_type (str): - Return type of the argument. The exact value - depends on the source system and the language. - definition_body (str): - The body of the routine. - bigquery_routine_spec (google.cloud.datacatalog_v1.types.BigQueryRoutineSpec): - Fields specific for BigQuery routines. - This field is a member of `oneof`_ ``system_spec``. - """ - class RoutineType(proto.Enum): - r"""The fine-grained type of the routine.""" - ROUTINE_TYPE_UNSPECIFIED = 0 - SCALAR_FUNCTION = 1 - PROCEDURE = 2 - - class Argument(proto.Message): - r"""Input or output argument of a function or stored procedure. - - Attributes: - name (str): - The name of the argument. A return argument - of a function might not have a name. - mode (google.cloud.datacatalog_v1.types.RoutineSpec.Argument.Mode): - Specifies whether the argument is input or - output. - type_ (str): - Type of the argument. The exact value depends - on the source system and the language. - """ - class Mode(proto.Enum): - r"""The input or output mode of the argument.""" - MODE_UNSPECIFIED = 0 - IN = 1 - OUT = 2 - INOUT = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - mode = proto.Field( - proto.ENUM, - number=2, - enum='RoutineSpec.Argument.Mode', - ) - type_ = proto.Field( - proto.STRING, - number=3, - ) - - routine_type = proto.Field( - proto.ENUM, - number=1, - enum=RoutineType, - ) - language = proto.Field( - proto.STRING, - number=2, - ) - routine_arguments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Argument, - ) - return_type = proto.Field( - proto.STRING, - number=4, - ) - definition_body = proto.Field( - proto.STRING, - number=5, - ) - bigquery_routine_spec = proto.Field( - proto.MESSAGE, - number=6, - oneof='system_spec', - message=bigquery.BigQueryRoutineSpec, - ) - - -class EntryGroup(proto.Message): - r"""Entry group metadata. - - An ``EntryGroup`` resource represents a logical grouping of zero or - more Data Catalog [Entry][google.cloud.datacatalog.v1.Entry] - resources. - - Attributes: - name (str): - The resource name of the entry group in URL - format. - Note: The entry group itself and its child - resources might not be stored in the location - specified in its name. - display_name (str): - A short name to identify the entry group, for - example, "analytics data - jan 2011". Default - value is an empty string. - description (str): - Entry group description. Can consist of - several sentences or paragraphs that describe - the entry group contents. Default value is an - empty string. - data_catalog_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): - Output only. Timestamps of the entry group. - Default value is empty. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - data_catalog_timestamps = proto.Field( - proto.MESSAGE, - number=4, - message=timestamps.SystemTimestamps, - ) - - -class CreateTagTemplateRequest(proto.Message): - r"""Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplate]. - - Attributes: - parent (str): - Required. The name of the project and the template location - `region `__. - tag_template_id (str): - Required. The ID of the tag template to create. - - The ID must contain only lowercase letters (a-z), numbers - (0-9), or underscores (_), and must start with a letter or - underscore. The maximum size is 64 bytes when encoded in - UTF-8. - tag_template (google.cloud.datacatalog_v1.types.TagTemplate): - Required. The tag template to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag_template_id = proto.Field( - proto.STRING, - number=3, - ) - tag_template = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.TagTemplate, - ) - - -class GetTagTemplateRequest(proto.Message): - r"""Request message for - [GetTagTemplate][google.cloud.datacatalog.v1.DataCatalog.GetTagTemplate]. - - Attributes: - name (str): - Required. The name of the tag template to - get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateTagTemplateRequest(proto.Message): - r"""Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplate]. - - Attributes: - tag_template (google.cloud.datacatalog_v1.types.TagTemplate): - Required. The template to update. The ``name`` field must be - set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on a tag template. - Currently, only ``display_name`` and - ``is_publicly_readable`` can be overwritten. - - If this parameter is absent or empty, all modifiable fields - are overwritten. If such fields are non-required and omitted - in the request body, their values are emptied. - - Note: Updating the ``is_publicly_readable`` field may - require up to 12 hours to take effect in search results. - Additionally, it also requires the - ``tagTemplates.getIamPolicy`` and - ``tagTemplates.setIamPolicy`` permissions. - """ - - tag_template = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_tags.TagTemplate, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteTagTemplateRequest(proto.Message): - r"""Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplate]. - - Attributes: - name (str): - Required. The name of the tag template to - delete. - force (bool): - Required. If true, deletes all tags that use this template. - - Currently, ``true`` is the only supported value. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class CreateTagRequest(proto.Message): - r"""Request message for - [CreateTag][google.cloud.datacatalog.v1.DataCatalog.CreateTag]. - - Attributes: - parent (str): - Required. The name of the resource to attach - this tag to. - Tags can be attached to entries or entry groups. - An entry can have up to 1000 attached tags. - - Note: The tag and its child resources might not - be stored in the location specified in its name. - tag (google.cloud.datacatalog_v1.types.Tag): - Required. The tag to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.Tag, - ) - - -class UpdateTagRequest(proto.Message): - r"""Request message for - [UpdateTag][google.cloud.datacatalog.v1.DataCatalog.UpdateTag]. - - Attributes: - tag (google.cloud.datacatalog_v1.types.Tag): - Required. The updated tag. The "name" field - must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Names of fields whose values to overwrite on a tag. - Currently, a tag has the only modifiable field with the name - ``fields``. - - In general, if this parameter is absent or empty, all - modifiable fields are overwritten. If such fields are - non-required and omitted in the request body, their values - are emptied. - """ - - tag = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_tags.Tag, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteTagRequest(proto.Message): - r"""Request message for - [DeleteTag][google.cloud.datacatalog.v1.DataCatalog.DeleteTag]. - - Attributes: - name (str): - Required. The name of the tag to delete. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTagTemplateFieldRequest(proto.Message): - r"""Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.CreateTagTemplateField]. - - Attributes: - parent (str): - Required. The name of the project and the template location - `region `__. - tag_template_field_id (str): - Required. The ID of the tag template field to create. - - Note: Adding a required field to an existing template is - *not* allowed. - - Field IDs can contain letters (both uppercase and - lowercase), numbers (0-9), underscores (_) and dashes (-). - Field IDs must be at least 1 character long and at most 128 - characters long. Field IDs must also be unique within their - template. - tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): - Required. The tag template field to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag_template_field_id = proto.Field( - proto.STRING, - number=2, - ) - tag_template_field = proto.Field( - proto.MESSAGE, - number=3, - message=gcd_tags.TagTemplateField, - ) - - -class UpdateTagTemplateFieldRequest(proto.Message): - r"""Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.UpdateTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template field. - tag_template_field (google.cloud.datacatalog_v1.types.TagTemplateField): - Required. The template to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Names of fields whose values to overwrite on an - individual field of a tag template. The following fields are - modifiable: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If this parameter is absent or empty, all modifiable fields - are overwritten. If such fields are non-required and omitted - in the request body, their values are emptied with one - exception: when updating an enum type, the provided values - are merged with the existing values. Therefore, enum values - can only be added, existing enum values cannot be deleted or - renamed. - - Additionally, updating a template field from optional to - required is *not* allowed. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - tag_template_field = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.TagTemplateField, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class RenameTagTemplateFieldRequest(proto.Message): - r"""Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template field. - new_tag_template_field_id (str): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - new_tag_template_field_id = proto.Field( - proto.STRING, - number=2, - ) - - -class RenameTagTemplateFieldEnumValueRequest(proto.Message): - r"""Request message for - [RenameTagTemplateFieldEnumValue][google.cloud.datacatalog.v1.DataCatalog.RenameTagTemplateFieldEnumValue]. - - Attributes: - name (str): - Required. The name of the enum field value. - new_enum_value_display_name (str): - Required. The new display name of the enum value. For - example, ``my_new_enum_value``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - new_enum_value_display_name = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteTagTemplateFieldRequest(proto.Message): - r"""Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1.DataCatalog.DeleteTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template field - to delete. - force (bool): - Required. If true, deletes this field from any tags that use - it. - - Currently, ``true`` is the only supported value. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListTagsRequest(proto.Message): - r"""Request message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - - Attributes: - parent (str): - Required. The name of the Data Catalog resource to list the - tags of. - - The resource can be an - [Entry][google.cloud.datacatalog.v1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1.EntryGroup] - (without ``/entries/{entries}`` at the end). - page_size (int): - The maximum number of tags to return. Default - is 10. Maximum limit is 1000. - page_token (str): - Pagination token that specifies the next page - to return. If empty, the first page is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTagsResponse(proto.Message): - r"""Response message for - [ListTags][google.cloud.datacatalog.v1.DataCatalog.ListTags]. - - Attributes: - tags (Sequence[google.cloud.datacatalog_v1.types.Tag]): - [Tag][google.cloud.datacatalog.v1.Tag] details. - next_page_token (str): - Pagination token of the next results page. - Empty if there are no more items in results. - """ - - @property - def raw_page(self): - return self - - tags = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_tags.Tag, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEntriesRequest(proto.Message): - r"""Request message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - - Attributes: - parent (str): - Required. The name of the entry group that - contains the entries to list. - Can be provided in URL format. - page_size (int): - The maximum number of items to return. Default is 10. - Maximum limit is 1000. Throws an invalid argument if - ``page_size`` is more than 1000. - page_token (str): - Pagination token that specifies the next page - to return. If empty, the first page is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return for each entry. If empty or omitted, - all fields are returned. - - For example, to return a list of entries with only the - ``name`` field, set ``read_mask`` to only one path with the - ``name`` value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class ListEntriesResponse(proto.Message): - r"""Response message for - [ListEntries][google.cloud.datacatalog.v1.DataCatalog.ListEntries]. - - Attributes: - entries (Sequence[google.cloud.datacatalog_v1.types.Entry]): - Entry details. - next_page_token (str): - Pagination token of the next results page. - Empty if there are no more items in results. - """ - - @property - def raw_page(self): - return self - - entries = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Entry', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py deleted file mode 100644 index 6d1800ee..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/gcs_fileset_spec.py +++ /dev/null @@ -1,115 +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.datacatalog_v1.types import timestamps - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'GcsFilesetSpec', - 'GcsFileSpec', - }, -) - - -class GcsFilesetSpec(proto.Message): - r"""Describes a Cloud Storage fileset entry. - - Attributes: - file_patterns (Sequence[str]): - Required. Patterns to identify a set of files in Google - Cloud Storage. - - For more information, see [Wildcard Names] - (https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames). - - Note: Currently, bucket wildcards are not supported. - - Examples of valid ``file_patterns``: - - - ``gs://bucket_name/dir/*``: matches all files in - ``bucket_name/dir`` directory - - ``gs://bucket_name/dir/**``: matches all files in - ``bucket_name/dir`` and all subdirectories - - ``gs://bucket_name/file*``: matches files prefixed by - ``file`` in ``bucket_name`` - - ``gs://bucket_name/??.txt``: matches files with two - characters followed by ``.txt`` in ``bucket_name`` - - ``gs://bucket_name/[aeiou].txt``: matches files that - contain a single vowel character followed by ``.txt`` in - ``bucket_name`` - - ``gs://bucket_name/[a-m].txt``: matches files that - contain ``a``, ``b``, ... or ``m`` followed by ``.txt`` - in ``bucket_name`` - - ``gs://bucket_name/a/*/b``: matches all files in - ``bucket_name`` that match the ``a/*/b`` pattern, such as - ``a/c/b``, ``a/d/b`` - - ``gs://another_bucket/a.txt``: matches - ``gs://another_bucket/a.txt`` - - You can combine wildcards to match complex sets of files, - for example: - - ``gs://bucket_name/[a-m]??.j*g`` - sample_gcs_file_specs (Sequence[google.cloud.datacatalog_v1.types.GcsFileSpec]): - Output only. Sample files contained in this - fileset, not all files contained in this fileset - are represented here. - """ - - file_patterns = proto.RepeatedField( - proto.STRING, - number=1, - ) - sample_gcs_file_specs = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='GcsFileSpec', - ) - - -class GcsFileSpec(proto.Message): - r"""Specification of a single file in Cloud Storage. - - Attributes: - file_path (str): - Required. Full file path. Example: - ``gs://bucket_name/a/b.txt``. - gcs_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): - Output only. Creation, modification, and - expiration timestamps of a Cloud Storage file. - size_bytes (int): - Output only. File size in bytes. - """ - - file_path = proto.Field( - proto.STRING, - number=1, - ) - gcs_timestamps = proto.Field( - proto.MESSAGE, - number=2, - message=timestamps.SystemTimestamps, - ) - size_bytes = proto.Field( - proto.INT64, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py deleted file mode 100644 index e212b29e..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanager.py +++ /dev/null @@ -1,495 +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.datacatalog_v1.types import timestamps -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'Taxonomy', - 'PolicyTag', - 'CreateTaxonomyRequest', - 'DeleteTaxonomyRequest', - 'UpdateTaxonomyRequest', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'GetTaxonomyRequest', - 'CreatePolicyTagRequest', - 'DeletePolicyTagRequest', - 'UpdatePolicyTagRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'GetPolicyTagRequest', - }, -) - - -class Taxonomy(proto.Message): - r"""A taxonomy is a collection of hierarchical policy tags that classify - data along a common axis. - - For example, a "data sensitivity" taxonomy might contain the - following policy tags: - - :: - - + PII - + Account number - + Age - + SSN - + Zipcode - + Financials - + Revenue - - A "data origin" taxonomy might contain the following policy tags: - - :: - - + User data - + Employee data - + Partner data - + Public data - - Attributes: - name (str): - Output only. Resource name of this taxonomy - in URL format. - Note: Policy tag manager generates unique - taxonomy IDs. - display_name (str): - Required. User-defined name of this taxonomy. - The name can't start or end with spaces, must - contain only Unicode letters, numbers, - underscores, dashes, and spaces, and be at most - 200 bytes long when encoded in UTF-8. - description (str): - Optional. Description of this taxonomy. If - not set, defaults to empty. - The description must contain only Unicode - characters, tabs, newlines, carriage returns, - and page breaks, and be at most 2000 bytes long - when encoded in UTF-8. - policy_tag_count (int): - Output only. Number of policy tags in this - taxonomy. - taxonomy_timestamps (google.cloud.datacatalog_v1.types.SystemTimestamps): - Output only. Creation and modification - timestamps of this taxonomy. - activated_policy_types (Sequence[google.cloud.datacatalog_v1.types.Taxonomy.PolicyType]): - Optional. A list of policy types that are - activated for this taxonomy. If not set, - defaults to an empty list. - """ - class PolicyType(proto.Enum): - r"""Defines policy types where the policy tags can be used for.""" - POLICY_TYPE_UNSPECIFIED = 0 - FINE_GRAINED_ACCESS_CONTROL = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - policy_tag_count = proto.Field( - proto.INT32, - number=4, - ) - taxonomy_timestamps = proto.Field( - proto.MESSAGE, - number=5, - message=timestamps.SystemTimestamps, - ) - activated_policy_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=PolicyType, - ) - - -class PolicyTag(proto.Message): - r"""Denotes one policy tag in a taxonomy, for example, SSN. - - Policy tags can be defined in a hierarchy. For example: - - :: - - + Geolocation - + LatLong - + City - + ZipCode - - Where the "Geolocation" policy tag contains three children. - - Attributes: - name (str): - Output only. Resource name of this policy tag - in the URL format. - The policy tag manager generates unique taxonomy - IDs and policy tag IDs. - display_name (str): - Required. User-defined name of this policy - tag. - The name can't start or end with spaces and must - be unique within the parent taxonomy, contain - only Unicode letters, numbers, underscores, - dashes and spaces, and be at most 200 bytes long - when encoded in UTF-8. - description (str): - Description of this policy tag. If not set, - defaults to empty. - The description must contain only Unicode - characters, tabs, newlines, carriage returns and - page breaks, and be at most 2000 bytes long when - encoded in UTF-8. - parent_policy_tag (str): - Resource name of this policy tag's parent - policy tag. If empty, this is a top level tag. - If not set, defaults to an empty string. - For example, for the "LatLong" policy tag in the - example above, this field contains the resource - name of the "Geolocation" policy tag, and, for - "Geolocation", this field is empty. - child_policy_tags (Sequence[str]): - Output only. Resource names of child policy - tags of this policy tag. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - parent_policy_tag = proto.Field( - proto.STRING, - number=4, - ) - child_policy_tags = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class CreateTaxonomyRequest(proto.Message): - r"""Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.CreateTaxonomy]. - - Attributes: - parent (str): - Required. Resource name of the project that - the taxonomy will belong to. - taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): - The taxonomy to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - taxonomy = proto.Field( - proto.MESSAGE, - number=2, - message='Taxonomy', - ) - - -class DeleteTaxonomyRequest(proto.Message): - r"""Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.DeleteTaxonomy]. - - Attributes: - name (str): - Required. Resource name of the taxonomy to - delete. - Note: All policy tags in this taxonomy are also - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateTaxonomyRequest(proto.Message): - r"""Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.UpdateTaxonomy]. - - Attributes: - taxonomy (google.cloud.datacatalog_v1.types.Taxonomy): - The taxonomy to update. You can update only - its description, display name, and activated - policy types. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies fields to update. If not set, defaults to all - fields you can update. - - For more information, see [FieldMask] - (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask). - """ - - taxonomy = proto.Field( - proto.MESSAGE, - number=1, - message='Taxonomy', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListTaxonomiesRequest(proto.Message): - r"""Request message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - - Attributes: - parent (str): - Required. Resource name of the project to - list the taxonomies of. - page_size (int): - The maximum number of items to return. Must - be a value between 1 and 1000 inclusively. If - not set, defaults to 50. - page_token (str): - The pagination token of the next results - page. If not set, the first page is returned. - The token is returned in the response to a - previous list request. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTaxonomiesResponse(proto.Message): - r"""Response message for - [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1.types.Taxonomy]): - Taxonomies that the project contains. - next_page_token (str): - Pagination token of the next results page. - Empty if there are no more results in the list. - """ - - @property - def raw_page(self): - return self - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Taxonomy', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTaxonomyRequest(proto.Message): - r"""Request message for - [GetTaxonomy][google.cloud.datacatalog.v1.PolicyTagManager.GetTaxonomy]. - - Attributes: - name (str): - Required. Resource name of the taxonomy to - get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreatePolicyTagRequest(proto.Message): - r"""Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.CreatePolicyTag]. - - Attributes: - parent (str): - Required. Resource name of the taxonomy that - the policy tag will belong to. - policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): - The policy tag to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - policy_tag = proto.Field( - proto.MESSAGE, - number=2, - message='PolicyTag', - ) - - -class DeletePolicyTagRequest(proto.Message): - r"""Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.DeletePolicyTag]. - - Attributes: - name (str): - Required. Resource name of the policy tag to - delete. - Note: All of its descendant policy tags are also - deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdatePolicyTagRequest(proto.Message): - r"""Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.UpdatePolicyTag]. - - Attributes: - policy_tag (google.cloud.datacatalog_v1.types.PolicyTag): - The policy tag to update. You can update only - its description, display name, and parent policy - tag fields. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies the fields to update. - - You can update only display name, description, and parent - policy tag. If not set, defaults to all updatable fields. - For more information, see [FieldMask] - (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask). - """ - - policy_tag = proto.Field( - proto.MESSAGE, - number=1, - message='PolicyTag', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListPolicyTagsRequest(proto.Message): - r"""Request message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - - Attributes: - parent (str): - Required. Resource name of the taxonomy to - list the policy tags of. - page_size (int): - The maximum number of items to return. Must - be a value between 1 and 1000 inclusively. - If not set, defaults to 50. - page_token (str): - The pagination token of the next results - page. If not set, returns the first page. - - The token is returned in the response to a - previous list request. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListPolicyTagsResponse(proto.Message): - r"""Response message for - [ListPolicyTags][google.cloud.datacatalog.v1.PolicyTagManager.ListPolicyTags]. - - Attributes: - policy_tags (Sequence[google.cloud.datacatalog_v1.types.PolicyTag]): - The policy tags that belong to the taxonomy. - next_page_token (str): - Pagination token of the next results page. - Empty if there are no more results in the list. - """ - - @property - def raw_page(self): - return self - - policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PolicyTag', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPolicyTagRequest(proto.Message): - r"""Request message for - [GetPolicyTag][google.cloud.datacatalog.v1.PolicyTagManager.GetPolicyTag]. - - Attributes: - name (str): - Required. Resource name of the policy tag. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py deleted file mode 100644 index 9b195aa3..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py +++ /dev/null @@ -1,281 +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.datacatalog_v1.types import policytagmanager - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'SerializedTaxonomy', - 'SerializedPolicyTag', - 'ReplaceTaxonomyRequest', - 'ImportTaxonomiesRequest', - 'InlineSource', - 'CrossRegionalSource', - 'ImportTaxonomiesResponse', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - }, -) - - -class SerializedTaxonomy(proto.Message): - r"""A nested protocol buffer that represents a taxonomy and the - hierarchy of its policy tags. Used for taxonomy replacement, - import, and export. - - Attributes: - display_name (str): - Required. Display name of the taxonomy. At - most 200 bytes when encoded in UTF-8. - description (str): - Description of the serialized taxonomy. At - most 2000 bytes when encoded in UTF-8. If not - set, defaults to an empty description. - policy_tags (Sequence[google.cloud.datacatalog_v1.types.SerializedPolicyTag]): - Top level policy tags associated with the - taxonomy, if any. - activated_policy_types (Sequence[google.cloud.datacatalog_v1.types.Taxonomy.PolicyType]): - A list of policy types that are activated per - taxonomy. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='SerializedPolicyTag', - ) - activated_policy_types = proto.RepeatedField( - proto.ENUM, - number=4, - enum=policytagmanager.Taxonomy.PolicyType, - ) - - -class SerializedPolicyTag(proto.Message): - r"""A nested protocol buffer that represents a policy tag and all - its descendants. - - Attributes: - policy_tag (str): - Resource name of the policy tag. - - This field is ignored when calling ``ImportTaxonomies``. - display_name (str): - Required. Display name of the policy tag. At - most 200 bytes when encoded in UTF-8. - description (str): - Description of the serialized policy tag. At - most 2000 bytes when encoded in UTF-8. If not - set, defaults to an empty description. - child_policy_tags (Sequence[google.cloud.datacatalog_v1.types.SerializedPolicyTag]): - Children of the policy tag, if any. - """ - - policy_tag = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - child_policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SerializedPolicyTag', - ) - - -class ReplaceTaxonomyRequest(proto.Message): - r"""Request message for - [ReplaceTaxonomy][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ReplaceTaxonomy]. - - Attributes: - name (str): - Required. Resource name of the taxonomy to - update. - serialized_taxonomy (google.cloud.datacatalog_v1.types.SerializedTaxonomy): - Required. Taxonomy to update along with its - child policy tags. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - serialized_taxonomy = proto.Field( - proto.MESSAGE, - number=2, - message='SerializedTaxonomy', - ) - - -class ImportTaxonomiesRequest(proto.Message): - r"""Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Resource name of project that the - imported taxonomies will belong to. - inline_source (google.cloud.datacatalog_v1.types.InlineSource): - Inline source taxonomy to import. - This field is a member of `oneof`_ ``source``. - cross_regional_source (google.cloud.datacatalog_v1.types.CrossRegionalSource): - Cross-regional source taxonomy to import. - This field is a member of `oneof`_ ``source``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - inline_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='InlineSource', - ) - cross_regional_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='CrossRegionalSource', - ) - - -class InlineSource(proto.Message): - r"""Inline source containing taxonomies to import. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1.types.SerializedTaxonomy]): - Required. Taxonomies to import. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SerializedTaxonomy', - ) - - -class CrossRegionalSource(proto.Message): - r"""Cross-regional source used to import an existing taxonomy - into a different region. - - Attributes: - taxonomy (str): - Required. The resource name of the source - taxonomy to import. - """ - - taxonomy = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportTaxonomiesResponse(proto.Message): - r"""Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ImportTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1.types.Taxonomy]): - Imported taxonomies. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=policytagmanager.Taxonomy, - ) - - -class ExportTaxonomiesRequest(proto.Message): - r"""Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Resource name of the project that - the exported taxonomies belong to. - taxonomies (Sequence[str]): - Required. Resource names of the taxonomies to - export. - serialized_taxonomies (bool): - Serialized export taxonomies that contain all - the policy tags as nested protocol buffers. - This field is a member of `oneof`_ ``destination``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - taxonomies = proto.RepeatedField( - proto.STRING, - number=2, - ) - serialized_taxonomies = proto.Field( - proto.BOOL, - number=3, - oneof='destination', - ) - - -class ExportTaxonomiesResponse(proto.Message): - r"""Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1.types.SerializedTaxonomy]): - List of taxonomies and policy tags as nested - protocol buffers. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SerializedTaxonomy', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py deleted file mode 100644 index 048a165a..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/schema.py +++ /dev/null @@ -1,99 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'Schema', - 'ColumnSchema', - }, -) - - -class Schema(proto.Message): - r"""Represents a schema, for example, a BigQuery, GoogleSQL, or - Avro schema. - - Attributes: - columns (Sequence[google.cloud.datacatalog_v1.types.ColumnSchema]): - The unified GoogleSQL-like schema of columns. - The overall maximum number of columns and nested - columns is 10,000. The maximum nested depth is - 15 levels. - """ - - columns = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ColumnSchema', - ) - - -class ColumnSchema(proto.Message): - r"""A column within a schema. Columns can be nested inside - other columns. - - Attributes: - column (str): - Required. Name of the column. - Must be a UTF-8 string without dots (.). - The maximum size is 64 bytes. - type_ (str): - Required. Type of the column. - Must be a UTF-8 string with the maximum size of - 128 bytes. - description (str): - Optional. Description of the column. Default - value is an empty string. - The description must be a UTF-8 string with the - maximum size of 2000 bytes. - mode (str): - Optional. A column's mode indicates whether values in this - column are required, nullable, or repeated. - - Only ``NULLABLE``, ``REQUIRED``, and ``REPEATED`` values are - supported. Default mode is ``NULLABLE``. - subcolumns (Sequence[google.cloud.datacatalog_v1.types.ColumnSchema]): - Optional. Schema of sub-columns. A column can - have zero or more sub-columns. - """ - - column = proto.Field( - proto.STRING, - number=6, - ) - type_ = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - mode = proto.Field( - proto.STRING, - number=3, - ) - subcolumns = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ColumnSchema', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py deleted file mode 100644 index bce6e920..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/search.py +++ /dev/null @@ -1,164 +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.datacatalog_v1.types import common -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'SearchResultType', - 'SearchCatalogResult', - }, -) - - -class SearchResultType(proto.Enum): - r"""The resource types that can be returned in search results.""" - SEARCH_RESULT_TYPE_UNSPECIFIED = 0 - ENTRY = 1 - TAG_TEMPLATE = 2 - ENTRY_GROUP = 3 - - -class SearchCatalogResult(proto.Message): - r"""Result in the response to a search request. - Each result captures details of one entry that matches the - search. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - search_result_type (google.cloud.datacatalog_v1.types.SearchResultType): - Type of the search result. - You can use this field to determine which get - method to call to fetch the full resource. - search_result_subtype (str): - Sub-type of the search result. - - A dot-delimited full type of the resource. The same type you - specify in the ``type`` search predicate. - - Examples: ``entry.table``, ``entry.dataStream``, - ``tagTemplate``. - relative_resource_name (str): - The relative name of the resource in URL format. - - Examples: - - - ``projects/{PROJECT_ID}/locations/{LOCATION_ID}/entryGroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}`` - - ``projects/{PROJECT_ID}/tagTemplates/{TAG_TEMPLATE_ID}`` - linked_resource (str): - The full name of the Google Cloud resource the entry belongs - to. - - For more information, see [Full Resource Name] - (/apis/design/resource_names#full_resource_name). - - Example: - - ``//bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID`` - modify_time (google.protobuf.timestamp_pb2.Timestamp): - The last modification timestamp of the entry - in the source system. - integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): - Output only. The source system that Data - Catalog automatically integrates with, such as - BigQuery, Cloud Pub/Sub, or Dataproc Metastore. - This field is a member of `oneof`_ ``system``. - user_specified_system (str): - Custom source system that you can manually - integrate Data Catalog with. - This field is a member of `oneof`_ ``system``. - fully_qualified_name (str): - Fully qualified name (FQN) of the resource. - - FQNs take two forms: - - - For non-regionalized resources: - - ``{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - - For regionalized resources: - - ``{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}`` - - Example for a DPMS table: - - ``dataproc_metastore:PROJECT_ID.LOCATION_ID.INSTANCE_ID.DATABASE_ID.TABLE_ID`` - display_name (str): - The display name of the result. - description (str): - Entry description that can consist of several - sentences or paragraphs that describe entry - contents. - """ - - search_result_type = proto.Field( - proto.ENUM, - number=1, - enum='SearchResultType', - ) - search_result_subtype = proto.Field( - proto.STRING, - number=2, - ) - relative_resource_name = proto.Field( - proto.STRING, - number=3, - ) - linked_resource = proto.Field( - proto.STRING, - number=4, - ) - modify_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - integrated_system = proto.Field( - proto.ENUM, - number=8, - oneof='system', - enum=common.IntegratedSystem, - ) - user_specified_system = proto.Field( - proto.STRING, - number=9, - oneof='system', - ) - fully_qualified_name = proto.Field( - proto.STRING, - number=10, - ) - display_name = proto.Field( - proto.STRING, - number=12, - ) - description = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py deleted file mode 100644 index e457cf11..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/table_spec.py +++ /dev/null @@ -1,161 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'TableSourceType', - 'BigQueryTableSpec', - 'ViewSpec', - 'TableSpec', - 'BigQueryDateShardedSpec', - }, -) - - -class TableSourceType(proto.Enum): - r"""Table source type.""" - TABLE_SOURCE_TYPE_UNSPECIFIED = 0 - BIGQUERY_VIEW = 2 - BIGQUERY_TABLE = 5 - BIGQUERY_MATERIALIZED_VIEW = 7 - - -class BigQueryTableSpec(proto.Message): - r"""Describes a BigQuery table. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - table_source_type (google.cloud.datacatalog_v1.types.TableSourceType): - Output only. The table source type. - view_spec (google.cloud.datacatalog_v1.types.ViewSpec): - Table view specification. Populated only if the - ``table_source_type`` is ``BIGQUERY_VIEW``. - This field is a member of `oneof`_ ``type_spec``. - table_spec (google.cloud.datacatalog_v1.types.TableSpec): - Specification of a BigQuery table. Populated only if the - ``table_source_type`` is ``BIGQUERY_TABLE``. - This field is a member of `oneof`_ ``type_spec``. - """ - - table_source_type = proto.Field( - proto.ENUM, - number=1, - enum='TableSourceType', - ) - view_spec = proto.Field( - proto.MESSAGE, - number=2, - oneof='type_spec', - message='ViewSpec', - ) - table_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='type_spec', - message='TableSpec', - ) - - -class ViewSpec(proto.Message): - r"""Table view specification. - - Attributes: - view_query (str): - Output only. The query that defines the table - view. - """ - - view_query = proto.Field( - proto.STRING, - number=1, - ) - - -class TableSpec(proto.Message): - r"""Normal BigQuery table specification. - - Attributes: - grouped_entry (str): - Output only. If the table is date-sharded, that is, it - matches the ``[prefix]YYYYMMDD`` name pattern, this field is - the Data Catalog resource name of the date-sharded grouped - entry. For example: - - ``projects/{PROJECT_ID}/locations/{LOCATION}/entrygroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}``. - - Otherwise, ``grouped_entry`` is empty. - """ - - grouped_entry = proto.Field( - proto.STRING, - number=1, - ) - - -class BigQueryDateShardedSpec(proto.Message): - r"""Specification for a group of BigQuery tables with the - ``[prefix]YYYYMMDD`` name pattern. - - For more information, see [Introduction to partitioned tables] - (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). - - Attributes: - dataset (str): - Output only. The Data Catalog resource name of the dataset - entry the current table belongs to. For example: - - ``projects/{PROJECT_ID}/locations/{LOCATION}/entrygroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}``. - table_prefix (str): - Output only. The table name prefix of the shards. - - The name of any given shard is ``[table_prefix]YYYYMMDD``. - For example, for the ``MyTable20180101`` shard, the - ``table_prefix`` is ``MyTable``. - shard_count (int): - Output only. Total number of shards. - latest_shard_resource (str): - Output only. BigQuery resource name of the - latest shard. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - table_prefix = proto.Field( - proto.STRING, - number=2, - ) - shard_count = proto.Field( - proto.INT64, - number=3, - ) - latest_shard_resource = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py deleted file mode 100644 index 6a6a8a8d..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/tags.py +++ /dev/null @@ -1,458 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'FieldType', - }, -) - - -class Tag(proto.Message): - r"""Tags contain custom metadata and are attached to Data Catalog - resources. Tags conform with the specification of their tag - template. - - See `Data Catalog - IAM `__ for - information on the permissions needed to create or view tags. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the tag in URL format - where tag ID is a system-generated identifier. - Note: The tag itself might not be stored in the - location specified in its name. - template (str): - Required. The resource name of the tag template this tag - uses. Example: - - ``projects/{PROJECT_ID}/locations/{LOCATION}/tagTemplates/{TAG_TEMPLATE_ID}`` - - This field cannot be modified after creation. - template_display_name (str): - Output only. The display name of the tag - template. - column (str): - Resources like entry can have schemas associated with them. - This scope allows you to attach tags to an individual column - based on that schema. - - To attach a tag to a nested column, separate column names - with a dot (``.``). Example: ``column.nested_column``. - This field is a member of `oneof`_ ``scope``. - fields (Sequence[google.cloud.datacatalog_v1.types.Tag.FieldsEntry]): - Required. Maps the ID of a tag field to its - value and additional information about that - field. - Tag template defines valid field IDs. A tag - must have at least 1 field and at most 500 - fields. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - template = proto.Field( - proto.STRING, - number=2, - ) - template_display_name = proto.Field( - proto.STRING, - number=5, - ) - column = proto.Field( - proto.STRING, - number=4, - oneof='scope', - ) - fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='TagField', - ) - - -class TagField(proto.Message): - r"""Contains the value and additional information on a field within a - [Tag][google.cloud.datacatalog.v1.Tag]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - display_name (str): - Output only. The display name of this field. - double_value (float): - The value of a tag field with a double type. - This field is a member of `oneof`_ ``kind``. - string_value (str): - The value of a tag field with a string type. - The maximum length is 2000 UTF-8 characters. - This field is a member of `oneof`_ ``kind``. - bool_value (bool): - The value of a tag field with a boolean type. - This field is a member of `oneof`_ ``kind``. - timestamp_value (google.protobuf.timestamp_pb2.Timestamp): - The value of a tag field with a timestamp - type. - This field is a member of `oneof`_ ``kind``. - enum_value (google.cloud.datacatalog_v1.types.TagField.EnumValue): - The value of a tag field with an enum type. - This value must be one of the allowed values - listed in this enum. - This field is a member of `oneof`_ ``kind``. - richtext_value (str): - The value of a tag field with a rich text - type. - The maximum length is 10 MiB as this value holds - HTML descriptions including encoded images. The - maximum length of the text without images is 100 - KiB. - This field is a member of `oneof`_ ``kind``. - order (int): - Output only. The order of this field with respect to other - fields in this tag. Can be set by - [Tag][google.cloud.datacatalog.v1.TagTemplateField.order]. - - For example, a higher value can indicate a more important - field. The value can be negative. Multiple fields can have - the same order, and field orders within a tag don't have to - be sequential. - """ - - class EnumValue(proto.Message): - r"""An enum value. - - Attributes: - display_name (str): - The display name of the enum value. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - - display_name = proto.Field( - proto.STRING, - number=1, - ) - double_value = proto.Field( - proto.DOUBLE, - number=2, - oneof='kind', - ) - string_value = proto.Field( - proto.STRING, - number=3, - oneof='kind', - ) - bool_value = proto.Field( - proto.BOOL, - number=4, - oneof='kind', - ) - timestamp_value = proto.Field( - proto.MESSAGE, - number=5, - oneof='kind', - message=timestamp_pb2.Timestamp, - ) - enum_value = proto.Field( - proto.MESSAGE, - number=6, - oneof='kind', - message=EnumValue, - ) - richtext_value = proto.Field( - proto.STRING, - number=8, - oneof='kind', - ) - order = proto.Field( - proto.INT32, - number=7, - ) - - -class TagTemplate(proto.Message): - r"""A tag template defines a tag that can have one or more typed fields. - - The template is used to create tags that are attached to GCP - resources. [Tag template roles] - (https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the template. For - example, see the [TagTemplate User] - (https://cloud.google.com/data-catalog/docs/how-to/template-user) - role that includes a permission to use the tag template to tag - resources. - - Attributes: - name (str): - The resource name of the tag template in URL - format. - Note: The tag template itself and its child - resources might not be stored in the location - specified in its name. - display_name (str): - Display name for this template. Defaults to an empty string. - - The name must contain only Unicode letters, numbers (0-9), - underscores (_), dashes (-), spaces ( ), and can't start or - end with spaces. The maximum length is 200 characters. - is_publicly_readable (bool): - Indicates whether this is a public tag template. - - Every user has view access to a *public* tag template by - default. This means that: - - - Every user can use this tag template to tag an entry. - - If an entry is tagged using the tag template, the tag is - always shown in the response to ``ListTags`` called on - the entry. - - To get the template using the GetTagTemplate method, you - need view access either on the project or the - organization the tag template resides in but no other - permission is needed. - - Operations on the tag template other than viewing (for - example, editing IAM policies) follow standard IAM - structures. - - Tags created with a public tag template are referred to as - public tags. - - You can search for a public tag by value with a simple - search query instead of using a ``tag:`` predicate. - - Public tag templates may not appear in search results - depending on scope, see: - [include_public_tag_templates][google.cloud.datacatalog.v1.SearchCatalogRequest.Scope.include_public_tag_templates] - - Note: If an `IAM domain - restriction `__ - is configured in the tag template's location, the public - access will not be enabled but the simple search for tag - values will still work. - fields (Sequence[google.cloud.datacatalog_v1.types.TagTemplate.FieldsEntry]): - Required. Map of tag template field IDs to the settings for - the field. This map is an exhaustive list of the allowed - fields. The map must contain at least one field and at most - 500 fields. - - The keys to this map are tag template field IDs. The IDs - have the following limitations: - - - Can contain uppercase and lowercase letters, numbers - (0-9) and underscores (_). - - Must be at least 1 character and at most 64 characters - long. - - Must start with a letter or underscore. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - is_publicly_readable = proto.Field( - proto.BOOL, - number=5, - ) - fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='TagTemplateField', - ) - - -class TagTemplateField(proto.Message): - r"""The template for an individual field within a tag template. - - Attributes: - name (str): - Output only. The resource name of the tag template field in - URL format. Example: - - ``projects/{PROJECT_ID}/locations/{LOCATION}/tagTemplates/{TAG_TEMPLATE}/fields/{FIELD}`` - - Note: The tag template field itself might not be stored in - the location specified in its name. - - The name must contain only letters (a-z, A-Z), numbers - (0-9), or underscores (_), and must start with a letter or - underscore. The maximum length is 64 characters. - display_name (str): - The display name for this field. Defaults to an empty - string. - - The name must contain only Unicode letters, numbers (0-9), - underscores (_), dashes (-), spaces ( ), and can't start or - end with spaces. The maximum length is 200 characters. - type_ (google.cloud.datacatalog_v1.types.FieldType): - Required. The type of value this tag field - can contain. - is_required (bool): - If true, this field is required. Defaults to - false. - description (str): - The description for this field. Defaults to - an empty string. - order (int): - The order of this field with respect to other - fields in this tag template. - - For example, a higher value can indicate a more - important field. The value can be negative. - Multiple fields can have the same order and - field orders within a tag don't have to be - sequential. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - display_name = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.MESSAGE, - number=2, - message='FieldType', - ) - is_required = proto.Field( - proto.BOOL, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - order = proto.Field( - proto.INT32, - number=5, - ) - - -class FieldType(proto.Message): - r""" - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - primitive_type (google.cloud.datacatalog_v1.types.FieldType.PrimitiveType): - Primitive types, such as string, boolean, - etc. - This field is a member of `oneof`_ ``type_decl``. - enum_type (google.cloud.datacatalog_v1.types.FieldType.EnumType): - An enum type. - This field is a member of `oneof`_ ``type_decl``. - """ - class PrimitiveType(proto.Enum): - r"""""" - PRIMITIVE_TYPE_UNSPECIFIED = 0 - DOUBLE = 1 - STRING = 2 - BOOL = 3 - TIMESTAMP = 4 - RICHTEXT = 5 - - class EnumType(proto.Message): - r""" - - Attributes: - allowed_values (Sequence[google.cloud.datacatalog_v1.types.FieldType.EnumType.EnumValue]): - The set of allowed values for this enum. - - This set must not be empty and can include up to 100 allowed - values. The display names of the values in this set must not - be empty and must be case-insensitively unique within this - set. - - The order of items in this set is preserved. This field can - be used to create, remove, and reorder enum values. To - rename enum values, use the - ``RenameTagTemplateFieldEnumValue`` method. - """ - - class EnumValue(proto.Message): - r""" - - Attributes: - display_name (str): - Required. The display name of the enum value. Must not be an - empty string. - - The name must contain only Unicode letters, numbers (0-9), - underscores (_), dashes (-), spaces ( ), and can't start or - end with spaces. The maximum length is 200 characters. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - - allowed_values = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FieldType.EnumType.EnumValue', - ) - - primitive_type = proto.Field( - proto.ENUM, - number=1, - oneof='type_decl', - enum=PrimitiveType, - ) - enum_type = proto.Field( - proto.MESSAGE, - number=2, - oneof='type_decl', - message=EnumType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py deleted file mode 100644 index fbda615c..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/timestamps.py +++ /dev/null @@ -1,67 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'SystemTimestamps', - }, -) - - -class SystemTimestamps(proto.Message): - r"""Timestamps associated with this resource in a particular - system. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Creation timestamp of the resource within the - given system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp of the last modification of the - resource or its metadata within a given system. - Note: Depending on the source system, not every - modification updates this timestamp. - For example, BigQuery timestamps every metadata - modification but not data or permission changes. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Expiration timestamp of the - resource within the given system. - Currently only applicable to BigQuery resources. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py b/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py deleted file mode 100644 index b8314499..00000000 --- a/owl-bot-staging/v1/google/cloud/datacatalog_v1/types/usage.py +++ /dev/null @@ -1,103 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1', - manifest={ - 'UsageStats', - 'UsageSignal', - }, -) - - -class UsageStats(proto.Message): - r"""Detailed statistics on the entry's usage. - - Usage statistics have the following limitations: - - - Only BigQuery tables have them. - - They only include BigQuery query jobs. - - They might be underestimated because wildcard table references - are not yet counted. For more information, see [Querying multiple - tables using a wildcard table] - (https://cloud.google.com/bigquery/docs/querying-wildcard-tables) - - Attributes: - total_completions (float): - The number of successful uses of the - underlying entry. - total_failures (float): - The number of failed attempts to use the - underlying entry. - total_cancellations (float): - The number of cancelled attempts to use the - underlying entry. - total_execution_time_for_completions_millis (float): - Total time spent only on successful uses, in - milliseconds. - """ - - total_completions = proto.Field( - proto.FLOAT, - number=1, - ) - total_failures = proto.Field( - proto.FLOAT, - number=2, - ) - total_cancellations = proto.Field( - proto.FLOAT, - number=3, - ) - total_execution_time_for_completions_millis = proto.Field( - proto.FLOAT, - number=4, - ) - - -class UsageSignal(proto.Message): - r"""The set of all usage signals that Data Catalog stores. - Note: Usually, these signals are updated daily. In rare cases, - an update may fail but will be performed again on the next day. - - Attributes: - update_time (google.protobuf.timestamp_pb2.Timestamp): - The end timestamp of the duration of usage - statistics. - usage_within_time_range (Sequence[google.cloud.datacatalog_v1.types.UsageSignal.UsageWithinTimeRangeEntry]): - Usage statistics over each of the predefined time ranges. - - Supported time ranges are ``{"24H", "7D", "30D"}``. - """ - - update_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - usage_within_time_range = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='UsageStats', - ) - - -__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 0fe4ab2a..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', '3.10']) -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/datacatalog_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.9') -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', '3.8', '3.9']) -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.9') -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_datacatalog_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_datacatalog_v1_keywords.py deleted file mode 100644 index 33d41aed..00000000 --- a/owl-bot-staging/v1/scripts/fixup_datacatalog_v1_keywords.py +++ /dev/null @@ -1,216 +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 datacatalogCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_entry': ('parent', 'entry_id', 'entry', ), - 'create_entry_group': ('parent', 'entry_group_id', 'entry_group', ), - 'create_policy_tag': ('parent', 'policy_tag', ), - 'create_tag': ('parent', 'tag', ), - 'create_tag_template': ('parent', 'tag_template_id', 'tag_template', ), - 'create_tag_template_field': ('parent', 'tag_template_field_id', 'tag_template_field', ), - 'create_taxonomy': ('parent', 'taxonomy', ), - 'delete_entry': ('name', ), - 'delete_entry_group': ('name', 'force', ), - 'delete_policy_tag': ('name', ), - 'delete_tag': ('name', ), - 'delete_tag_template': ('name', 'force', ), - 'delete_tag_template_field': ('name', 'force', ), - 'delete_taxonomy': ('name', ), - 'export_taxonomies': ('parent', 'taxonomies', 'serialized_taxonomies', ), - 'get_entry': ('name', ), - 'get_entry_group': ('name', 'read_mask', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_policy_tag': ('name', ), - 'get_tag_template': ('name', ), - 'get_taxonomy': ('name', ), - 'import_taxonomies': ('parent', 'inline_source', 'cross_regional_source', ), - 'list_entries': ('parent', 'page_size', 'page_token', 'read_mask', ), - 'list_entry_groups': ('parent', 'page_size', 'page_token', ), - 'list_policy_tags': ('parent', 'page_size', 'page_token', ), - 'list_tags': ('parent', 'page_size', 'page_token', ), - 'list_taxonomies': ('parent', 'page_size', 'page_token', ), - 'lookup_entry': ('linked_resource', 'sql_resource', 'fully_qualified_name', ), - 'rename_tag_template_field': ('name', 'new_tag_template_field_id', ), - 'rename_tag_template_field_enum_value': ('name', 'new_enum_value_display_name', ), - 'replace_taxonomy': ('name', 'serialized_taxonomy', ), - 'search_catalog': ('scope', 'query', 'page_size', 'page_token', 'order_by', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_entry': ('entry', 'update_mask', ), - 'update_entry_group': ('entry_group', 'update_mask', ), - 'update_policy_tag': ('policy_tag', 'update_mask', ), - 'update_tag': ('tag', 'update_mask', ), - 'update_tag_template': ('tag_template', 'update_mask', ), - 'update_tag_template_field': ('name', 'tag_template_field', 'update_mask', ), - 'update_taxonomy': ('taxonomy', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=datacatalogCallTransformer(), -): - """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 datacatalog 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 f76df593..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,55 +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-datacatalog', - 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.28.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.19.4', - 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', - ), - 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/datacatalog_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_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/datacatalog_v1/test_data_catalog.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py deleted file mode 100644 index 383f19f6..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_data_catalog.py +++ /dev/null @@ -1,8365 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1.services.data_catalog import DataCatalogAsyncClient -from google.cloud.datacatalog_v1.services.data_catalog import DataCatalogClient -from google.cloud.datacatalog_v1.services.data_catalog import pagers -from google.cloud.datacatalog_v1.services.data_catalog import transports -from google.cloud.datacatalog_v1.types import bigquery -from google.cloud.datacatalog_v1.types import common -from google.cloud.datacatalog_v1.types import data_source -from google.cloud.datacatalog_v1.types import datacatalog -from google.cloud.datacatalog_v1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1.types import schema -from google.cloud.datacatalog_v1.types import search -from google.cloud.datacatalog_v1.types import table_spec -from google.cloud.datacatalog_v1.types import tags -from google.cloud.datacatalog_v1.types import timestamps -from google.cloud.datacatalog_v1.types import usage -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DataCatalogClient._get_default_mtls_endpoint(None) is None - assert DataCatalogClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DataCatalogClient, - DataCatalogAsyncClient, -]) -def test_data_catalog_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DataCatalogGrpcTransport, "grpc"), - (transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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", [ - DataCatalogClient, - DataCatalogAsyncClient, -]) -def test_data_catalog_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 == 'datacatalog.googleapis.com:443' - - -def test_data_catalog_client_get_transport_class(): - transport = DataCatalogClient.get_transport_class() - available_transports = [ - transports.DataCatalogGrpcTransport, - ] - assert transport in available_transports - - transport = DataCatalogClient.get_transport_class("grpc") - assert transport == transports.DataCatalogGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) -@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) -def test_data_catalog_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(DataCatalogClient, '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(DataCatalogClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "true"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "false"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) -@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_catalog_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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(transport=transport_name, 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", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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(transport=transport_name, 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_catalog_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1.services.data_catalog.transports.DataCatalogGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DataCatalogClient( - 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_search_catalog(transport: str = 'grpc', request_type=datacatalog.SearchCatalogRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.search_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchCatalogPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_search_catalog_from_dict(): - test_search_catalog(request_type=dict) - - -def test_search_catalog_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 = DataCatalogClient( - 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.search_catalog), - '__call__') as call: - client.search_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - -@pytest.mark.asyncio -async def test_search_catalog_async(transport: str = 'grpc_asyncio', request_type=datacatalog.SearchCatalogRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.search_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchCatalogAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_search_catalog_async_from_dict(): - await test_search_catalog_async(request_type=dict) - - -def test_search_catalog_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_catalog( - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) - assert args[0].query == 'query_value' - - -def test_search_catalog_flattened_error(): - client = DataCatalogClient( - 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.search_catalog( - datacatalog.SearchCatalogRequest(), - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_value', - ) - - -@pytest.mark.asyncio -async def test_search_catalog_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_catalog( - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) - assert args[0].query == 'query_value' - - -@pytest.mark.asyncio -async def test_search_catalog_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.search_catalog( - datacatalog.SearchCatalogRequest(), - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_value', - ) - - -def test_search_catalog_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.search_catalog(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, search.SearchCatalogResult) - for i in results) - -def test_search_catalog_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search_catalog(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_search_catalog_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_catalog(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, search.SearchCatalogResult) - for i in responses) - -@pytest.mark.asyncio -async def test_search_catalog_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_catalog(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_entry_group(transport: str = 'grpc', request_type=datacatalog.CreateEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_entry_group_from_dict(): - test_create_entry_group(request_type=dict) - - -def test_create_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.create_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_create_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_entry_group_async_from_dict(): - await test_create_entry_group_async(request_type=dict) - - -def test_create_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.create_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entry_group( - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' - assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') - - -def test_create_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.CreateEntryGroupRequest(), - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entry_group( - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' - assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') - - -@pytest.mark.asyncio -async def test_create_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.CreateEntryGroupRequest(), - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(name='name_value'), - ) - - -def test_get_entry_group(transport: str = 'grpc', request_type=datacatalog.GetEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_entry_group_from_dict(): - test_get_entry_group(request_type=dict) - - -def test_get_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.get_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_get_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_entry_group_async_from_dict(): - await test_get_entry_group_async(request_type=dict) - - -def test_get_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.get_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entry_group( - name='name_value', - read_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].name == 'name_value' - assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_get_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.GetEntryGroupRequest(), - name='name_value', - read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_get_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entry_group( - name='name_value', - read_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].name == 'name_value' - assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_get_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.GetEntryGroupRequest(), - name='name_value', - read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_entry_group(transport: str = 'grpc', request_type=datacatalog.UpdateEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_entry_group_from_dict(): - test_update_entry_group(request_type=dict) - - -def test_update_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.update_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_update_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_entry_group_async_from_dict(): - await test_update_entry_group_async(request_type=dict) - - -def test_update_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryGroupRequest() - - request.entry_group.name = 'entry_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'entry_group.name=entry_group.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryGroupRequest() - - request.entry_group.name = 'entry_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.update_entry_group(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', - 'entry_group.name=entry_group.name/value', - ) in kw['metadata'] - - -def test_update_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entry_group( - entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.UpdateEntryGroupRequest(), - entry_group=datacatalog.EntryGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entry_group( - entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.UpdateEntryGroupRequest(), - entry_group=datacatalog.EntryGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_entry_group(transport: str = 'grpc', request_type=datacatalog.DeleteEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entry_group_from_dict(): - test_delete_entry_group(request_type=dict) - - -def test_delete_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.delete_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_delete_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entry_group_async_from_dict(): - await test_delete_entry_group_async(request_type=dict) - - -def test_delete_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__call__') as call: - call.return_value = None - client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__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_entry_group( - 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_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.DeleteEntryGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__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_entry_group( - 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_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.DeleteEntryGroupRequest(), - name='name_value', - ) - - -def test_list_entry_groups(transport: str = 'grpc', request_type=datacatalog.ListEntryGroupsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntryGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entry_groups_from_dict(): - test_list_entry_groups(request_type=dict) - - -def test_list_entry_groups_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 = DataCatalogClient( - 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_entry_groups), - '__call__') as call: - client.list_entry_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - -@pytest.mark.asyncio -async def test_list_entry_groups_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntryGroupsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntryGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_entry_groups_async_from_dict(): - await test_list_entry_groups_async(request_type=dict) - - -def test_list_entry_groups_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntryGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - call.return_value = datacatalog.ListEntryGroupsResponse() - client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_groups_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntryGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) - await client.list_entry_groups(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_entry_groups_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entry_groups( - 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_entry_groups_flattened_error(): - client = DataCatalogClient( - 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_entry_groups( - datacatalog.ListEntryGroupsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_entry_groups_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entry_groups( - 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_entry_groups_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_groups( - datacatalog.ListEntryGroupsRequest(), - parent='parent_value', - ) - - -def test_list_entry_groups_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entry_groups(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, datacatalog.EntryGroup) - for i in results) - -def test_list_entry_groups_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entry_groups(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_entry_groups_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entry_groups(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, datacatalog.EntryGroup) - for i in responses) - -@pytest.mark.asyncio -async def test_list_entry_groups_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entry_groups(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_entry(transport: str = 'grpc', request_type=datacatalog.CreateEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), - ) - response = client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_entry_from_dict(): - test_create_entry(request_type=dict) - - -def test_create_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.create_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - -@pytest.mark.asyncio -async def test_create_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_entry_async_from_dict(): - await test_create_entry_async(request_type=dict) - - -def test_create_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.create_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entry( - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(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].entry_id == 'entry_id_value' - assert args[0].entry == datacatalog.Entry(name='name_value') - - -def test_create_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.CreateEntryRequest(), - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entry( - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(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].entry_id == 'entry_id_value' - assert args[0].entry == datacatalog.Entry(name='name_value') - - -@pytest.mark.asyncio -async def test_create_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.CreateEntryRequest(), - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(name='name_value'), - ) - - -def test_update_entry(transport: str = 'grpc', request_type=datacatalog.UpdateEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), - ) - response = client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_entry_from_dict(): - test_update_entry(request_type=dict) - - -def test_update_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.update_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - -@pytest.mark.asyncio -async def test_update_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_entry_async_from_dict(): - await test_update_entry_async(request_type=dict) - - -def test_update_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryRequest() - - request.entry.name = 'entry.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'entry.name=entry.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryRequest() - - request.entry.name = 'entry.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.update_entry(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', - 'entry.name=entry.name/value', - ) in kw['metadata'] - - -def test_update_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entry( - entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.UpdateEntryRequest(), - entry=datacatalog.Entry(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entry( - entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.UpdateEntryRequest(), - entry=datacatalog.Entry(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_entry(transport: str = 'grpc', request_type=datacatalog.DeleteEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entry_from_dict(): - test_delete_entry(request_type=dict) - - -def test_delete_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.delete_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - -@pytest.mark.asyncio -async def test_delete_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entry_async_from_dict(): - await test_delete_entry_async(request_type=dict) - - -def test_delete_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__call__') as call: - call.return_value = None - client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__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_entry( - 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_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.DeleteEntryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__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_entry( - 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_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.DeleteEntryRequest(), - name='name_value', - ) - - -def test_get_entry(transport: str = 'grpc', request_type=datacatalog.GetEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), - ) - response = client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_entry_from_dict(): - test_get_entry(request_type=dict) - - -def test_get_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.get_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - -@pytest.mark.asyncio -async def test_get_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_entry_async_from_dict(): - await test_get_entry_async(request_type=dict) - - -def test_get_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.get_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entry( - 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_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.GetEntryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entry( - 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_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.GetEntryRequest(), - name='name_value', - ) - - -def test_lookup_entry(transport: str = 'grpc', request_type=datacatalog.LookupEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - database_table_spec=datacatalog.DatabaseTableSpec(type_=datacatalog.DatabaseTableSpec.TableType.NATIVE), - ) - response = client.lookup_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_lookup_entry_from_dict(): - test_lookup_entry(request_type=dict) - - -def test_lookup_entry_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 = DataCatalogClient( - 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.lookup_entry), - '__call__') as call: - client.lookup_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - -@pytest.mark.asyncio -async def test_lookup_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.LookupEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - fully_qualified_name='fully_qualified_name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.lookup_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.fully_qualified_name == 'fully_qualified_name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_lookup_entry_async_from_dict(): - await test_lookup_entry_async(request_type=dict) - - -def test_list_entries(transport: str = 'grpc', request_type=datacatalog.ListEntriesRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entries_from_dict(): - test_list_entries(request_type=dict) - - -def test_list_entries_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 = DataCatalogClient( - 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_entries), - '__call__') as call: - client.list_entries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - -@pytest.mark.asyncio -async def test_list_entries_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntriesRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_entries_async_from_dict(): - await test_list_entries_async(request_type=dict) - - -def test_list_entries_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - call.return_value = datacatalog.ListEntriesResponse() - client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entries_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) - await client.list_entries(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_entries_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entries( - 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_entries_flattened_error(): - client = DataCatalogClient( - 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_entries( - datacatalog.ListEntriesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_entries_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entries( - 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_entries_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entries( - datacatalog.ListEntriesRequest(), - parent='parent_value', - ) - - -def test_list_entries_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entries(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, datacatalog.Entry) - for i in results) - -def test_list_entries_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entries(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_entries_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entries(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, datacatalog.Entry) - for i in responses) - -@pytest.mark.asyncio -async def test_list_entries_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entries(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_tag_template(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - ) - response = client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -def test_create_tag_template_from_dict(): - test_create_tag_template(request_type=dict) - - -def test_create_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.create_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_create_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - )) - response = await client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -@pytest.mark.asyncio -async def test_create_tag_template_async_from_dict(): - await test_create_tag_template_async(request_type=dict) - - -def test_create_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.create_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag_template( - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' - assert args[0].tag_template == tags.TagTemplate(name='name_value') - - -def test_create_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.CreateTagTemplateRequest(), - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag_template( - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' - assert args[0].tag_template == tags.TagTemplate(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.CreateTagTemplateRequest(), - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(name='name_value'), - ) - - -def test_get_tag_template(transport: str = 'grpc', request_type=datacatalog.GetTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - ) - response = client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -def test_get_tag_template_from_dict(): - test_get_tag_template(request_type=dict) - - -def test_get_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.get_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_get_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - )) - response = await client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -@pytest.mark.asyncio -async def test_get_tag_template_async_from_dict(): - await test_get_tag_template_async(request_type=dict) - - -def test_get_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.get_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tag_template( - 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_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.GetTagTemplateRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tag_template( - 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_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.GetTagTemplateRequest(), - name='name_value', - ) - - -def test_update_tag_template(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - ) - response = client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -def test_update_tag_template_from_dict(): - test_update_tag_template(request_type=dict) - - -def test_update_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.update_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_update_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - is_publicly_readable=True, - )) - response = await client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_publicly_readable is True - - -@pytest.mark.asyncio -async def test_update_tag_template_async_from_dict(): - await test_update_tag_template_async(request_type=dict) - - -def test_update_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateRequest() - - request.tag_template.name = 'tag_template.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag_template.name=tag_template.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateRequest() - - request.tag_template.name = 'tag_template.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.update_tag_template(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', - 'tag_template.name=tag_template.name/value', - ) in kw['metadata'] - - -def test_update_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_template( - tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.UpdateTagTemplateRequest(), - tag_template=tags.TagTemplate(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_template( - tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.UpdateTagTemplateRequest(), - tag_template=tags.TagTemplate(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_tag_template(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_template_from_dict(): - test_delete_tag_template(request_type=dict) - - -def test_delete_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.delete_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_template_async_from_dict(): - await test_delete_tag_template_async(request_type=dict) - - -def test_delete_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__call__') as call: - call.return_value = None - client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__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_tag_template( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -def test_delete_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.DeleteTagTemplateRequest(), - name='name_value', - force=True, - ) - - -@pytest.mark.asyncio -async def test_delete_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__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_tag_template( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -@pytest.mark.asyncio -async def test_delete_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.DeleteTagTemplateRequest(), - name='name_value', - force=True, - ) - - -def test_create_tag_template_field(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - ) - response = client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -def test_create_tag_template_field_from_dict(): - test_create_tag_template_field(request_type=dict) - - -def test_create_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.create_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_create_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - )) - response = await client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_create_tag_template_field_async_from_dict(): - await test_create_tag_template_field_async(request_type=dict) - - -def test_create_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateFieldRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateFieldRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.create_tag_template_field(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_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag_template_field( - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - - -def test_create_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.CreateTagTemplateFieldRequest(), - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag_template_field( - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.CreateTagTemplateFieldRequest(), - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - ) - - -def test_update_tag_template_field(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - ) - response = client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -def test_update_tag_template_field_from_dict(): - test_update_tag_template_field(request_type=dict) - - -def test_update_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.update_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_update_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - )) - response = await client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_update_tag_template_field_async_from_dict(): - await test_update_tag_template_field_async(request_type=dict) - - -def test_update_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_update_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.update_tag_template_field(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_update_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_template_field( - name='name_value', - tag_template_field=tags.TagTemplateField(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].name == 'name_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.UpdateTagTemplateFieldRequest(), - name='name_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_template_field( - name='name_value', - tag_template_field=tags.TagTemplateField(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].name == 'name_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.UpdateTagTemplateFieldRequest(), - name='name_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_rename_tag_template_field(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - ) - response = client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -def test_rename_tag_template_field_from_dict(): - test_rename_tag_template_field(request_type=dict) - - -def test_rename_tag_template_field_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 = DataCatalogClient( - 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.rename_tag_template_field), - '__call__') as call: - client.rename_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - )) - response = await client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_async_from_dict(): - await test_rename_tag_template_field_async(request_type=dict) - - -def test_rename_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_rename_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.rename_tag_template_field(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_rename_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.rename_tag_template_field( - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' - - -def test_rename_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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.rename_tag_template_field( - datacatalog.RenameTagTemplateFieldRequest(), - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.rename_tag_template_field( - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.rename_tag_template_field( - datacatalog.RenameTagTemplateFieldRequest(), - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - -def test_rename_tag_template_field_enum_value(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldEnumValueRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - ) - response = client.rename_tag_template_field_enum_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -def test_rename_tag_template_field_enum_value_from_dict(): - test_rename_tag_template_field_enum_value(request_type=dict) - - -def test_rename_tag_template_field_enum_value_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 = DataCatalogClient( - 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.rename_tag_template_field_enum_value), - '__call__') as call: - client.rename_tag_template_field_enum_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_enum_value_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldEnumValueRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - description='description_value', - order=540, - )) - response = await client.rename_tag_template_field_enum_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldEnumValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.description == 'description_value' - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_enum_value_async_from_dict(): - await test_rename_tag_template_field_enum_value_async(request_type=dict) - - -def test_rename_tag_template_field_enum_value_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldEnumValueRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.rename_tag_template_field_enum_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_rename_tag_template_field_enum_value_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldEnumValueRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.rename_tag_template_field_enum_value(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_rename_tag_template_field_enum_value_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.rename_tag_template_field_enum_value( - name='name_value', - new_enum_value_display_name='new_enum_value_display_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' - assert args[0].new_enum_value_display_name == 'new_enum_value_display_name_value' - - -def test_rename_tag_template_field_enum_value_flattened_error(): - client = DataCatalogClient( - 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.rename_tag_template_field_enum_value( - datacatalog.RenameTagTemplateFieldEnumValueRequest(), - name='name_value', - new_enum_value_display_name='new_enum_value_display_name_value', - ) - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_enum_value_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field_enum_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.rename_tag_template_field_enum_value( - name='name_value', - new_enum_value_display_name='new_enum_value_display_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' - assert args[0].new_enum_value_display_name == 'new_enum_value_display_name_value' - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_enum_value_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.rename_tag_template_field_enum_value( - datacatalog.RenameTagTemplateFieldEnumValueRequest(), - name='name_value', - new_enum_value_display_name='new_enum_value_display_name_value', - ) - - -def test_delete_tag_template_field(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_template_field_from_dict(): - test_delete_tag_template_field(request_type=dict) - - -def test_delete_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.delete_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_async_from_dict(): - await test_delete_tag_template_field_async(request_type=dict) - - -def test_delete_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__call__') as call: - call.return_value = None - client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag_template_field(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_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__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_tag_template_field( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -def test_delete_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.DeleteTagTemplateFieldRequest(), - name='name_value', - force=True, - ) - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__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_tag_template_field( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.DeleteTagTemplateFieldRequest(), - name='name_value', - force=True, - ) - - -def test_create_tag(transport: str = 'grpc', request_type=datacatalog.CreateTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - column='column_value', - ) - response = client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -def test_create_tag_from_dict(): - test_create_tag(request_type=dict) - - -def test_create_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.create_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - -@pytest.mark.asyncio -async def test_create_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - )) - response = await client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -@pytest.mark.asyncio -async def test_create_tag_async_from_dict(): - await test_create_tag_async(request_type=dict) - - -def test_create_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - call.return_value = tags.Tag() - client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - await client.create_tag(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_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag( - parent='parent_value', - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - - -def test_create_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.CreateTagRequest(), - parent='parent_value', - tag=tags.Tag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag( - parent='parent_value', - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.CreateTagRequest(), - parent='parent_value', - tag=tags.Tag(name='name_value'), - ) - - -def test_update_tag(transport: str = 'grpc', request_type=datacatalog.UpdateTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - column='column_value', - ) - response = client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -def test_update_tag_from_dict(): - test_update_tag(request_type=dict) - - -def test_update_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.update_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - -@pytest.mark.asyncio -async def test_update_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - )) - response = await client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -@pytest.mark.asyncio -async def test_update_tag_async_from_dict(): - await test_update_tag_async(request_type=dict) - - -def test_update_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagRequest() - - request.tag.name = 'tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - call.return_value = tags.Tag() - client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag.name=tag.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagRequest() - - request.tag.name = 'tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - await client.update_tag(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', - 'tag.name=tag.name/value', - ) in kw['metadata'] - - -def test_update_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag( - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.UpdateTagRequest(), - tag=tags.Tag(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag( - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.UpdateTagRequest(), - tag=tags.Tag(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_tag(transport: str = 'grpc', request_type=datacatalog.DeleteTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_from_dict(): - test_delete_tag(request_type=dict) - - -def test_delete_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.delete_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_async_from_dict(): - await test_delete_tag_async(request_type=dict) - - -def test_delete_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__call__') as call: - call.return_value = None - client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag(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_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__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_tag( - 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_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.DeleteTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__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_tag( - 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_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.DeleteTagRequest(), - name='name_value', - ) - - -def test_list_tags(transport: str = 'grpc', request_type=datacatalog.ListTagsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tags_from_dict(): - test_list_tags(request_type=dict) - - -def test_list_tags_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 = DataCatalogClient( - 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_tags), - '__call__') as call: - client.list_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - -@pytest.mark.asyncio -async def test_list_tags_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListTagsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tags_async_from_dict(): - await test_list_tags_async(request_type=dict) - - -def test_list_tags_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - call.return_value = datacatalog.ListTagsResponse() - client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tags_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) - await client.list_tags(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_tags_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tags( - 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_tags_flattened_error(): - client = DataCatalogClient( - 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_tags( - datacatalog.ListTagsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_tags_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tags( - 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_tags_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tags( - datacatalog.ListTagsRequest(), - parent='parent_value', - ) - - -def test_list_tags_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_tags(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, tags.Tag) - for i in results) - -def test_list_tags_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tags(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_tags_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tags(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, tags.Tag) - for i in responses) - -@pytest.mark.asyncio -async def test_list_tags_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_tags(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataCatalogClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_set_iam_policy_async_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_set_iam_policy_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy(request={ - 'resource': 'resource_value', - 'policy': policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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].resource == 'resource_value' - - -def test_set_iam_policy_flattened_error(): - client = DataCatalogClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_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].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataCatalogClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_get_iam_policy_async_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_get_iam_policy_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_get_iam_policy_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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].resource == 'resource_value' - - -def test_get_iam_policy_flattened_error(): - client = DataCatalogClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_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].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = DataCatalogClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - )) - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_test_iam_permissions_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions(request={ - 'resource': 'resource_value', - 'permissions': ['permissions_value'], - } - ) - call.assert_called() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DataCatalogClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DataCatalogGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DataCatalogGrpcTransport, - transports.DataCatalogGrpcAsyncIOTransport, -]) -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 = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DataCatalogGrpcTransport, - ) - -def test_data_catalog_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DataCatalogTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_data_catalog_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DataCatalogTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search_catalog', - 'create_entry_group', - 'get_entry_group', - 'update_entry_group', - 'delete_entry_group', - 'list_entry_groups', - 'create_entry', - 'update_entry', - 'delete_entry', - 'get_entry', - 'lookup_entry', - 'list_entries', - 'create_tag_template', - 'get_tag_template', - 'update_tag_template', - 'delete_tag_template', - 'create_tag_template_field', - 'update_tag_template_field', - 'rename_tag_template_field', - 'rename_tag_template_field_enum_value', - 'delete_tag_template_field', - 'create_tag', - 'update_tag', - 'delete_tag', - 'list_tags', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_data_catalog_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.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataCatalogTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_data_catalog_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.datacatalog_v1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataCatalogTransport() - adc.assert_called_once() - - -def test_data_catalog_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) - DataCatalogClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DataCatalogGrpcTransport, - transports.DataCatalogGrpcAsyncIOTransport, - ], -) -def test_data_catalog_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,grpc_helpers", - [ - (transports.DataCatalogGrpcTransport, grpc_helpers), - (transports.DataCatalogGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_data_catalog_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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_catalog_host_no_port(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_data_catalog_host_with_port(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_data_catalog_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataCatalogGrpcTransport( - 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_catalog_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataCatalogGrpcAsyncIOTransport( - 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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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_entry_path(): - project = "squid" - location = "clam" - entry_group = "whelk" - entry = "octopus" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) - actual = DataCatalogClient.entry_path(project, location, entry_group, entry) - assert expected == actual - - -def test_parse_entry_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "entry_group": "cuttlefish", - "entry": "mussel", - } - path = DataCatalogClient.entry_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_entry_path(path) - assert expected == actual - -def test_entry_group_path(): - project = "winkle" - location = "nautilus" - entry_group = "scallop" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) - actual = DataCatalogClient.entry_group_path(project, location, entry_group) - assert expected == actual - - -def test_parse_entry_group_path(): - expected = { - "project": "abalone", - "location": "squid", - "entry_group": "clam", - } - path = DataCatalogClient.entry_group_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_entry_group_path(path) - assert expected == actual - -def test_tag_path(): - project = "whelk" - location = "octopus" - entry_group = "oyster" - entry = "nudibranch" - tag = "cuttlefish" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) - actual = DataCatalogClient.tag_path(project, location, entry_group, entry, tag) - assert expected == actual - - -def test_parse_tag_path(): - expected = { - "project": "mussel", - "location": "winkle", - "entry_group": "nautilus", - "entry": "scallop", - "tag": "abalone", - } - path = DataCatalogClient.tag_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_path(path) - assert expected == actual - -def test_tag_template_path(): - project = "squid" - location = "clam" - tag_template = "whelk" - expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) - actual = DataCatalogClient.tag_template_path(project, location, tag_template) - assert expected == actual - - -def test_parse_tag_template_path(): - expected = { - "project": "octopus", - "location": "oyster", - "tag_template": "nudibranch", - } - path = DataCatalogClient.tag_template_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_template_path(path) - assert expected == actual - -def test_tag_template_field_path(): - project = "cuttlefish" - location = "mussel" - tag_template = "winkle" - field = "nautilus" - expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) - actual = DataCatalogClient.tag_template_field_path(project, location, tag_template, field) - assert expected == actual - - -def test_parse_tag_template_field_path(): - expected = { - "project": "scallop", - "location": "abalone", - "tag_template": "squid", - "field": "clam", - } - path = DataCatalogClient.tag_template_field_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_template_field_path(path) - assert expected == actual - -def test_tag_template_field_enum_value_path(): - project = "whelk" - location = "octopus" - tag_template = "oyster" - tag_template_field_id = "nudibranch" - enum_value_display_name = "cuttlefish" - expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{tag_template_field_id}/enumValues/{enum_value_display_name}".format(project=project, location=location, tag_template=tag_template, tag_template_field_id=tag_template_field_id, enum_value_display_name=enum_value_display_name, ) - actual = DataCatalogClient.tag_template_field_enum_value_path(project, location, tag_template, tag_template_field_id, enum_value_display_name) - assert expected == actual - - -def test_parse_tag_template_field_enum_value_path(): - expected = { - "project": "mussel", - "location": "winkle", - "tag_template": "nautilus", - "tag_template_field_id": "scallop", - "enum_value_display_name": "abalone", - } - path = DataCatalogClient.tag_template_field_enum_value_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_template_field_enum_value_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DataCatalogClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DataCatalogClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DataCatalogClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DataCatalogClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DataCatalogClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DataCatalogClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DataCatalogClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DataCatalogClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DataCatalogClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DataCatalogClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.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.DataCatalogTransport, '_prep_wrapped_messages') as prep: - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DataCatalogTransport, '_prep_wrapped_messages') as prep: - transport_class = DataCatalogClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py deleted file mode 100644 index 248c1a93..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py +++ /dev/null @@ -1,4247 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1.services.policy_tag_manager import PolicyTagManagerAsyncClient -from google.cloud.datacatalog_v1.services.policy_tag_manager import PolicyTagManagerClient -from google.cloud.datacatalog_v1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1.services.policy_tag_manager import transports -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PolicyTagManagerClient._get_default_mtls_endpoint(None) is None - assert PolicyTagManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PolicyTagManagerClient, - PolicyTagManagerAsyncClient, -]) -def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PolicyTagManagerGrpcTransport, "grpc"), - (transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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", [ - PolicyTagManagerClient, - PolicyTagManagerAsyncClient, -]) -def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_client_get_transport_class(): - transport = PolicyTagManagerClient.get_transport_class() - available_transports = [ - transports.PolicyTagManagerGrpcTransport, - ] - assert transport in available_transports - - transport = PolicyTagManagerClient.get_transport_class("grpc") - assert transport == transports.PolicyTagManagerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) -@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) -def test_policy_tag_manager_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(PolicyTagManagerClient, '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(PolicyTagManagerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "true"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "false"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) -@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_policy_tag_manager_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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(transport=transport_name, 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", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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(transport=transport_name, 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_policy_tag_manager_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PolicyTagManagerClient( - 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_create_taxonomy(transport: str = 'grpc', request_type=policytagmanager.CreateTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_create_taxonomy_from_dict(): - test_create_taxonomy(request_type=dict) - - -def test_create_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.create_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_create_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreateTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_create_taxonomy_async_from_dict(): - await test_create_taxonomy_async(request_type=dict) - - -def test_create_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreateTaxonomyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreateTaxonomyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.create_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_taxonomy( - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -def test_create_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.CreateTaxonomyRequest(), - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_taxonomy( - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -@pytest.mark.asyncio -async def test_create_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.CreateTaxonomyRequest(), - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -def test_delete_taxonomy(transport: str = 'grpc', request_type=policytagmanager.DeleteTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_taxonomy_from_dict(): - test_delete_taxonomy(request_type=dict) - - -def test_delete_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.delete_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_delete_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeleteTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_taxonomy_async_from_dict(): - await test_delete_taxonomy_async(request_type=dict) - - -def test_delete_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeleteTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__call__') as call: - call.return_value = None - client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeleteTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__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_taxonomy( - 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_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.DeleteTaxonomyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__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_taxonomy( - 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_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.DeleteTaxonomyRequest(), - name='name_value', - ) - - -def test_update_taxonomy(transport: str = 'grpc', request_type=policytagmanager.UpdateTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_update_taxonomy_from_dict(): - test_update_taxonomy(request_type=dict) - - -def test_update_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.update_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_update_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdateTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_update_taxonomy_async_from_dict(): - await test_update_taxonomy_async(request_type=dict) - - -def test_update_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdateTaxonomyRequest() - - request.taxonomy.name = 'taxonomy.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'taxonomy.name=taxonomy.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdateTaxonomyRequest() - - request.taxonomy.name = 'taxonomy.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.update_taxonomy(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', - 'taxonomy.name=taxonomy.name/value', - ) in kw['metadata'] - - -def test_update_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_taxonomy( - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -def test_update_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.UpdateTaxonomyRequest(), - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_taxonomy( - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -@pytest.mark.asyncio -async def test_update_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.UpdateTaxonomyRequest(), - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -def test_list_taxonomies(transport: str = 'grpc', request_type=policytagmanager.ListTaxonomiesRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTaxonomiesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_taxonomies_from_dict(): - test_list_taxonomies(request_type=dict) - - -def test_list_taxonomies_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 = PolicyTagManagerClient( - 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_taxonomies), - '__call__') as call: - client.list_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_list_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListTaxonomiesRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTaxonomiesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_taxonomies_async_from_dict(): - await test_list_taxonomies_async(request_type=dict) - - -def test_list_taxonomies_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - call.return_value = policytagmanager.ListTaxonomiesResponse() - client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_taxonomies_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) - await client.list_taxonomies(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_taxonomies_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_taxonomies( - 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_taxonomies_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomies( - policytagmanager.ListTaxonomiesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_taxonomies_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_taxonomies( - 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_taxonomies_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomies( - policytagmanager.ListTaxonomiesRequest(), - parent='parent_value', - ) - - -def test_list_taxonomies_pager(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_taxonomies(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, policytagmanager.Taxonomy) - for i in results) - -def test_list_taxonomies_pages(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_taxonomies(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_taxonomies_async_pager(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_taxonomies(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, policytagmanager.Taxonomy) - for i in responses) - -@pytest.mark.asyncio -async def test_list_taxonomies_async_pages(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_taxonomies(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_taxonomy(transport: str = 'grpc', request_type=policytagmanager.GetTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_get_taxonomy_from_dict(): - test_get_taxonomy(request_type=dict) - - -def test_get_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.get_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_get_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_get_taxonomy_async_from_dict(): - await test_get_taxonomy_async(request_type=dict) - - -def test_get_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.get_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_taxonomy( - 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_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.GetTaxonomyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_taxonomy( - 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_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.GetTaxonomyRequest(), - name='name_value', - ) - - -def test_create_policy_tag(transport: str = 'grpc', request_type=policytagmanager.CreatePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_create_policy_tag_from_dict(): - test_create_policy_tag(request_type=dict) - - -def test_create_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.create_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_create_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreatePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_create_policy_tag_async_from_dict(): - await test_create_policy_tag_async(request_type=dict) - - -def test_create_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreatePolicyTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreatePolicyTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.create_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_policy_tag( - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -def test_create_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.CreatePolicyTagRequest(), - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_policy_tag( - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -@pytest.mark.asyncio -async def test_create_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.CreatePolicyTagRequest(), - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -def test_delete_policy_tag(transport: str = 'grpc', request_type=policytagmanager.DeletePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_policy_tag_from_dict(): - test_delete_policy_tag(request_type=dict) - - -def test_delete_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.delete_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_delete_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeletePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_policy_tag_async_from_dict(): - await test_delete_policy_tag_async(request_type=dict) - - -def test_delete_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeletePolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__call__') as call: - call.return_value = None - client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeletePolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__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_policy_tag( - 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_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.DeletePolicyTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__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_policy_tag( - 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_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.DeletePolicyTagRequest(), - name='name_value', - ) - - -def test_update_policy_tag(transport: str = 'grpc', request_type=policytagmanager.UpdatePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_update_policy_tag_from_dict(): - test_update_policy_tag(request_type=dict) - - -def test_update_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.update_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_update_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdatePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_update_policy_tag_async_from_dict(): - await test_update_policy_tag_async(request_type=dict) - - -def test_update_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdatePolicyTagRequest() - - request.policy_tag.name = 'policy_tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'policy_tag.name=policy_tag.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdatePolicyTagRequest() - - request.policy_tag.name = 'policy_tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.update_policy_tag(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', - 'policy_tag.name=policy_tag.name/value', - ) in kw['metadata'] - - -def test_update_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_policy_tag( - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -def test_update_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.UpdatePolicyTagRequest(), - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_policy_tag( - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -@pytest.mark.asyncio -async def test_update_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.UpdatePolicyTagRequest(), - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -def test_list_policy_tags(transport: str = 'grpc', request_type=policytagmanager.ListPolicyTagsRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPolicyTagsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_policy_tags_from_dict(): - test_list_policy_tags(request_type=dict) - - -def test_list_policy_tags_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 = PolicyTagManagerClient( - 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_policy_tags), - '__call__') as call: - client.list_policy_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - -@pytest.mark.asyncio -async def test_list_policy_tags_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListPolicyTagsRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPolicyTagsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_policy_tags_async_from_dict(): - await test_list_policy_tags_async(request_type=dict) - - -def test_list_policy_tags_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListPolicyTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - call.return_value = policytagmanager.ListPolicyTagsResponse() - client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_policy_tags_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListPolicyTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) - await client.list_policy_tags(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_policy_tags_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_policy_tags( - 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_policy_tags_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tags( - policytagmanager.ListPolicyTagsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_policy_tags_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_policy_tags( - 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_policy_tags_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tags( - policytagmanager.ListPolicyTagsRequest(), - parent='parent_value', - ) - - -def test_list_policy_tags_pager(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_policy_tags(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, policytagmanager.PolicyTag) - for i in results) - -def test_list_policy_tags_pages(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - pages = list(client.list_policy_tags(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_policy_tags_async_pager(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_policy_tags(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, policytagmanager.PolicyTag) - for i in responses) - -@pytest.mark.asyncio -async def test_list_policy_tags_async_pages(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_policy_tags(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_policy_tag(transport: str = 'grpc', request_type=policytagmanager.GetPolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_get_policy_tag_from_dict(): - test_get_policy_tag(request_type=dict) - - -def test_get_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.get_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - -@pytest.mark.asyncio -async def test_get_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetPolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_get_policy_tag_async_from_dict(): - await test_get_policy_tag_async(request_type=dict) - - -def test_get_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetPolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetPolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.get_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_policy_tag( - 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_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.GetPolicyTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_policy_tag( - 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_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.GetPolicyTagRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTagManagerClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_get_iam_policy_async_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_get_iam_policy_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTagManagerClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_set_iam_policy_async_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_set_iam_policy_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy(request={ - 'resource': 'resource_value', - 'policy': policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = PolicyTagManagerClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - )) - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_test_iam_permissions_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions(request={ - 'resource': 'resource_value', - 'permissions': ['permissions_value'], - } - ) - call.assert_called() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PolicyTagManagerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PolicyTagManagerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PolicyTagManagerGrpcTransport, - transports.PolicyTagManagerGrpcAsyncIOTransport, -]) -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 = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PolicyTagManagerGrpcTransport, - ) - -def test_policy_tag_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PolicyTagManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_policy_tag_manager_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PolicyTagManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_taxonomy', - 'delete_taxonomy', - 'update_taxonomy', - 'list_taxonomies', - 'get_taxonomy', - 'create_policy_tag', - 'delete_policy_tag', - 'update_policy_tag', - 'list_policy_tags', - 'get_policy_tag', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_policy_tag_manager_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.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_policy_tag_manager_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.datacatalog_v1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerTransport() - adc.assert_called_once() - - -def test_policy_tag_manager_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) - PolicyTagManagerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PolicyTagManagerGrpcTransport, - transports.PolicyTagManagerGrpcAsyncIOTransport, - ], -) -def test_policy_tag_manager_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,grpc_helpers", - [ - (transports.PolicyTagManagerGrpcTransport, grpc_helpers), - (transports.PolicyTagManagerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_policy_tag_manager_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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_policy_tag_manager_host_no_port(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_host_with_port(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_policy_tag_manager_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerGrpcTransport( - 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_policy_tag_manager_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerGrpcAsyncIOTransport( - 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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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_policy_tag_path(): - project = "squid" - location = "clam" - taxonomy = "whelk" - policy_tag = "octopus" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) - actual = PolicyTagManagerClient.policy_tag_path(project, location, taxonomy, policy_tag) - assert expected == actual - - -def test_parse_policy_tag_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "taxonomy": "cuttlefish", - "policy_tag": "mussel", - } - path = PolicyTagManagerClient.policy_tag_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_policy_tag_path(path) - assert expected == actual - -def test_taxonomy_path(): - project = "winkle" - location = "nautilus" - taxonomy = "scallop" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - actual = PolicyTagManagerClient.taxonomy_path(project, location, taxonomy) - assert expected == actual - - -def test_parse_taxonomy_path(): - expected = { - "project": "abalone", - "location": "squid", - "taxonomy": "clam", - } - path = PolicyTagManagerClient.taxonomy_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_taxonomy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PolicyTagManagerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = PolicyTagManagerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = PolicyTagManagerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = PolicyTagManagerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PolicyTagManagerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = PolicyTagManagerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = PolicyTagManagerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = PolicyTagManagerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.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 = PolicyTagManagerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = PolicyTagManagerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.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.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: - transport_class = PolicyTagManagerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py b/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py deleted file mode 100644 index 0028b014..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py +++ /dev/null @@ -1,1379 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient -from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient -from google.cloud.datacatalog_v1.services.policy_tag_manager_serialization import transports -from google.cloud.datacatalog_v1.types import policytagmanager -from google.cloud.datacatalog_v1.types import policytagmanagerserialization -from google.cloud.datacatalog_v1.types import timestamps -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(None) is None - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PolicyTagManagerSerializationClient, - PolicyTagManagerSerializationAsyncClient, -]) -def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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", [ - PolicyTagManagerSerializationClient, - PolicyTagManagerSerializationAsyncClient, -]) -def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_serialization_client_get_transport_class(): - transport = PolicyTagManagerSerializationClient.get_transport_class() - available_transports = [ - transports.PolicyTagManagerSerializationGrpcTransport, - ] - assert transport in available_transports - - transport = PolicyTagManagerSerializationClient.get_transport_class("grpc") - assert transport == transports.PolicyTagManagerSerializationGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) -@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) -def test_policy_tag_manager_serialization_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(PolicyTagManagerSerializationClient, '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(PolicyTagManagerSerializationClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "true"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "false"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) -@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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_policy_tag_manager_serialization_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PolicyTagManagerSerializationClient( - 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_replace_taxonomy(transport: str = 'grpc', request_type=policytagmanagerserialization.ReplaceTaxonomyRequest): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.replace_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_replace_taxonomy_from_dict(): - test_replace_taxonomy(request_type=dict) - - -def test_replace_taxonomy_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 = PolicyTagManagerSerializationClient( - 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.replace_taxonomy), - '__call__') as call: - client.replace_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_replace_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ReplaceTaxonomyRequest): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - policy_tag_count=1715, - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.replace_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ReplaceTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.policy_tag_count == 1715 - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_replace_taxonomy_async_from_dict(): - await test_replace_taxonomy_async(request_type=dict) - - -def test_replace_taxonomy_field_headers(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ReplaceTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.replace_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_replace_taxonomy_field_headers_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ReplaceTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.replace_taxonomy(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_import_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse( - ) - response = client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) - - -def test_import_taxonomies_from_dict(): - test_import_taxonomies(request_type=dict) - - -def test_import_taxonomies_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 = PolicyTagManagerSerializationClient( - 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.import_taxonomies), - '__call__') as call: - client.import_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_import_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse( - )) - response = await client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) - - -@pytest.mark.asyncio -async def test_import_taxonomies_async_from_dict(): - await test_import_taxonomies_async(request_type=dict) - - -def test_import_taxonomies_field_headers(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ImportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse() - client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_import_taxonomies_field_headers_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ImportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse()) - await client.import_taxonomies(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_export_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse( - ) - response = client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) - - -def test_export_taxonomies_from_dict(): - test_export_taxonomies(request_type=dict) - - -def test_export_taxonomies_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 = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - client.export_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_export_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse( - )) - response = await client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) - - -@pytest.mark.asyncio -async def test_export_taxonomies_async_from_dict(): - await test_export_taxonomies_async(request_type=dict) - - -def test_export_taxonomies_field_headers(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ExportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse() - client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_export_taxonomies_field_headers_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ExportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse()) - await client.export_taxonomies(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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PolicyTagManagerSerializationClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PolicyTagManagerSerializationGrpcTransport, - transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, -]) -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 = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PolicyTagManagerSerializationGrpcTransport, - ) - -def test_policy_tag_manager_serialization_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PolicyTagManagerSerializationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_policy_tag_manager_serialization_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PolicyTagManagerSerializationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'replace_taxonomy', - 'import_taxonomies', - 'export_taxonomies', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_policy_tag_manager_serialization_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.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerSerializationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_policy_tag_manager_serialization_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.datacatalog_v1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerSerializationTransport() - adc.assert_called_once() - - -def test_policy_tag_manager_serialization_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) - PolicyTagManagerSerializationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PolicyTagManagerSerializationGrpcTransport, - transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, - ], -) -def test_policy_tag_manager_serialization_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,grpc_helpers", - [ - (transports.PolicyTagManagerSerializationGrpcTransport, grpc_helpers), - (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_policy_tag_manager_serialization_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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_policy_tag_manager_serialization_host_no_port(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_serialization_host_with_port(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_policy_tag_manager_serialization_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - 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_policy_tag_manager_serialization_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( - 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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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_taxonomy_path(): - project = "squid" - location = "clam" - taxonomy = "whelk" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - actual = PolicyTagManagerSerializationClient.taxonomy_path(project, location, taxonomy) - assert expected == actual - - -def test_parse_taxonomy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "taxonomy": "nudibranch", - } - path = PolicyTagManagerSerializationClient.taxonomy_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_taxonomy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PolicyTagManagerSerializationClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = PolicyTagManagerSerializationClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = PolicyTagManagerSerializationClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = PolicyTagManagerSerializationClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PolicyTagManagerSerializationClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = PolicyTagManagerSerializationClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = PolicyTagManagerSerializationClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = PolicyTagManagerSerializationClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = PolicyTagManagerSerializationClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = PolicyTagManagerSerializationClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.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.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: - transport_class = PolicyTagManagerSerializationClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc deleted file mode 100644 index ac5fa2e9..00000000 --- a/owl-bot-staging/v1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/datacatalog/__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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in deleted file mode 100644 index 0e9fef34..00000000 --- a/owl-bot-staging/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/datacatalog *.py -recursive-include google/cloud/datacatalog_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst deleted file mode 100644 index 8f53b244..00000000 --- a/owl-bot-staging/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Datacatalog 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 Datacatalog 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py deleted file mode 100644 index 67b364b2..00000000 --- a/owl-bot-staging/v1beta1/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-datacatalog 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-datacatalog" -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-datacatalog-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-datacatalog.tex", - u"google-cloud-datacatalog 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-datacatalog", - u"Google Cloud Datacatalog 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-datacatalog", - u"google-cloud-datacatalog Documentation", - author, - "google-cloud-datacatalog", - "GAPIC library for Google Cloud Datacatalog 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/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst deleted file mode 100644 index 82ca26f3..00000000 --- a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/data_catalog.rst +++ /dev/null @@ -1,10 +0,0 @@ -DataCatalog ------------------------------ - -.. automodule:: google.cloud.datacatalog_v1beta1.services.data_catalog - :members: - :inherited-members: - -.. automodule:: google.cloud.datacatalog_v1beta1.services.data_catalog.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst deleted file mode 100644 index 8971945c..00000000 --- a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager.rst +++ /dev/null @@ -1,10 +0,0 @@ -PolicyTagManager ----------------------------------- - -.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager - :members: - :inherited-members: - -.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst deleted file mode 100644 index aed4c56c..00000000 --- a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/policy_tag_manager_serialization.rst +++ /dev/null @@ -1,6 +0,0 @@ -PolicyTagManagerSerialization ------------------------------------------------ - -.. automodule:: google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst deleted file mode 100644 index 4f762e1c..00000000 --- a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/services.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Cloud Datacatalog v1beta1 API -================================================= -.. toctree:: - :maxdepth: 2 - - data_catalog - policy_tag_manager - policy_tag_manager_serialization diff --git a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst deleted file mode 100644 index 687d8391..00000000 --- a/owl-bot-staging/v1beta1/docs/datacatalog_v1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Datacatalog v1beta1 API -============================================== - -.. automodule:: google.cloud.datacatalog_v1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst deleted file mode 100644 index ae7dac5f..00000000 --- a/owl-bot-staging/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - datacatalog_v1beta1/services - datacatalog_v1beta1/types diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py deleted file mode 100644 index 8e9095b9..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog/__init__.py +++ /dev/null @@ -1,171 +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.datacatalog_v1beta1.services.data_catalog.client import DataCatalogClient -from google.cloud.datacatalog_v1beta1.services.data_catalog.async_client import DataCatalogAsyncClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager.client import PolicyTagManagerClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager.async_client import PolicyTagManagerAsyncClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.client import PolicyTagManagerSerializationClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.async_client import PolicyTagManagerSerializationAsyncClient - -from google.cloud.datacatalog_v1beta1.types.common import IntegratedSystem -from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateEntryGroupRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateEntryRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagTemplateFieldRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import CreateTagTemplateRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteEntryGroupRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteEntryRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagTemplateFieldRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import DeleteTagTemplateRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import Entry -from google.cloud.datacatalog_v1beta1.types.datacatalog import EntryGroup -from google.cloud.datacatalog_v1beta1.types.datacatalog import GetEntryGroupRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import GetEntryRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import GetTagTemplateRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntriesRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntriesResponse -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntryGroupsRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListEntryGroupsResponse -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListTagsRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import ListTagsResponse -from google.cloud.datacatalog_v1beta1.types.datacatalog import LookupEntryRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import RenameTagTemplateFieldRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import SearchCatalogRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import SearchCatalogResponse -from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateEntryGroupRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateEntryRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagTemplateFieldRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import UpdateTagTemplateRequest -from google.cloud.datacatalog_v1beta1.types.datacatalog import EntryType -from google.cloud.datacatalog_v1beta1.types.gcs_fileset_spec import GcsFilesetSpec -from google.cloud.datacatalog_v1beta1.types.gcs_fileset_spec import GcsFileSpec -from google.cloud.datacatalog_v1beta1.types.policytagmanager import CreatePolicyTagRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import CreateTaxonomyRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import DeletePolicyTagRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import DeleteTaxonomyRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import GetPolicyTagRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import GetTaxonomyRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListPolicyTagsRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListPolicyTagsResponse -from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListTaxonomiesRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import ListTaxonomiesResponse -from google.cloud.datacatalog_v1beta1.types.policytagmanager import PolicyTag -from google.cloud.datacatalog_v1beta1.types.policytagmanager import Taxonomy -from google.cloud.datacatalog_v1beta1.types.policytagmanager import UpdatePolicyTagRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanager import UpdateTaxonomyRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ExportTaxonomiesRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ExportTaxonomiesResponse -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ImportTaxonomiesRequest -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import ImportTaxonomiesResponse -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import InlineSource -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import SerializedPolicyTag -from google.cloud.datacatalog_v1beta1.types.policytagmanagerserialization import SerializedTaxonomy -from google.cloud.datacatalog_v1beta1.types.schema import ColumnSchema -from google.cloud.datacatalog_v1beta1.types.schema import Schema -from google.cloud.datacatalog_v1beta1.types.search import SearchCatalogResult -from google.cloud.datacatalog_v1beta1.types.search import SearchResultType -from google.cloud.datacatalog_v1beta1.types.table_spec import BigQueryDateShardedSpec -from google.cloud.datacatalog_v1beta1.types.table_spec import BigQueryTableSpec -from google.cloud.datacatalog_v1beta1.types.table_spec import TableSpec -from google.cloud.datacatalog_v1beta1.types.table_spec import ViewSpec -from google.cloud.datacatalog_v1beta1.types.table_spec import TableSourceType -from google.cloud.datacatalog_v1beta1.types.tags import FieldType -from google.cloud.datacatalog_v1beta1.types.tags import Tag -from google.cloud.datacatalog_v1beta1.types.tags import TagField -from google.cloud.datacatalog_v1beta1.types.tags import TagTemplate -from google.cloud.datacatalog_v1beta1.types.tags import TagTemplateField -from google.cloud.datacatalog_v1beta1.types.timestamps import SystemTimestamps - -__all__ = ('DataCatalogClient', - 'DataCatalogAsyncClient', - 'PolicyTagManagerClient', - 'PolicyTagManagerAsyncClient', - 'PolicyTagManagerSerializationClient', - 'PolicyTagManagerSerializationAsyncClient', - 'IntegratedSystem', - 'CreateEntryGroupRequest', - 'CreateEntryRequest', - 'CreateTagRequest', - 'CreateTagTemplateFieldRequest', - 'CreateTagTemplateRequest', - 'DeleteEntryGroupRequest', - 'DeleteEntryRequest', - 'DeleteTagRequest', - 'DeleteTagTemplateFieldRequest', - 'DeleteTagTemplateRequest', - 'Entry', - 'EntryGroup', - 'GetEntryGroupRequest', - 'GetEntryRequest', - 'GetTagTemplateRequest', - 'ListEntriesRequest', - 'ListEntriesResponse', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'ListTagsRequest', - 'ListTagsResponse', - 'LookupEntryRequest', - 'RenameTagTemplateFieldRequest', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'UpdateEntryGroupRequest', - 'UpdateEntryRequest', - 'UpdateTagRequest', - 'UpdateTagTemplateFieldRequest', - 'UpdateTagTemplateRequest', - 'EntryType', - 'GcsFilesetSpec', - 'GcsFileSpec', - 'CreatePolicyTagRequest', - 'CreateTaxonomyRequest', - 'DeletePolicyTagRequest', - 'DeleteTaxonomyRequest', - 'GetPolicyTagRequest', - 'GetTaxonomyRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'PolicyTag', - 'Taxonomy', - 'UpdatePolicyTagRequest', - 'UpdateTaxonomyRequest', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - 'ImportTaxonomiesRequest', - 'ImportTaxonomiesResponse', - 'InlineSource', - 'SerializedPolicyTag', - 'SerializedTaxonomy', - 'ColumnSchema', - 'Schema', - 'SearchCatalogResult', - 'SearchResultType', - 'BigQueryDateShardedSpec', - 'BigQueryTableSpec', - 'TableSpec', - 'ViewSpec', - 'TableSourceType', - 'FieldType', - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'SystemTimestamps', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed b/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed deleted file mode 100644 index bb4088a3..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py deleted file mode 100644 index dc3c7a23..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/__init__.py +++ /dev/null @@ -1,172 +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_catalog import DataCatalogClient -from .services.data_catalog import DataCatalogAsyncClient -from .services.policy_tag_manager import PolicyTagManagerClient -from .services.policy_tag_manager import PolicyTagManagerAsyncClient -from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient -from .services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient - -from .types.common import IntegratedSystem -from .types.datacatalog import CreateEntryGroupRequest -from .types.datacatalog import CreateEntryRequest -from .types.datacatalog import CreateTagRequest -from .types.datacatalog import CreateTagTemplateFieldRequest -from .types.datacatalog import CreateTagTemplateRequest -from .types.datacatalog import DeleteEntryGroupRequest -from .types.datacatalog import DeleteEntryRequest -from .types.datacatalog import DeleteTagRequest -from .types.datacatalog import DeleteTagTemplateFieldRequest -from .types.datacatalog import DeleteTagTemplateRequest -from .types.datacatalog import Entry -from .types.datacatalog import EntryGroup -from .types.datacatalog import GetEntryGroupRequest -from .types.datacatalog import GetEntryRequest -from .types.datacatalog import GetTagTemplateRequest -from .types.datacatalog import ListEntriesRequest -from .types.datacatalog import ListEntriesResponse -from .types.datacatalog import ListEntryGroupsRequest -from .types.datacatalog import ListEntryGroupsResponse -from .types.datacatalog import ListTagsRequest -from .types.datacatalog import ListTagsResponse -from .types.datacatalog import LookupEntryRequest -from .types.datacatalog import RenameTagTemplateFieldRequest -from .types.datacatalog import SearchCatalogRequest -from .types.datacatalog import SearchCatalogResponse -from .types.datacatalog import UpdateEntryGroupRequest -from .types.datacatalog import UpdateEntryRequest -from .types.datacatalog import UpdateTagRequest -from .types.datacatalog import UpdateTagTemplateFieldRequest -from .types.datacatalog import UpdateTagTemplateRequest -from .types.datacatalog import EntryType -from .types.gcs_fileset_spec import GcsFilesetSpec -from .types.gcs_fileset_spec import GcsFileSpec -from .types.policytagmanager import CreatePolicyTagRequest -from .types.policytagmanager import CreateTaxonomyRequest -from .types.policytagmanager import DeletePolicyTagRequest -from .types.policytagmanager import DeleteTaxonomyRequest -from .types.policytagmanager import GetPolicyTagRequest -from .types.policytagmanager import GetTaxonomyRequest -from .types.policytagmanager import ListPolicyTagsRequest -from .types.policytagmanager import ListPolicyTagsResponse -from .types.policytagmanager import ListTaxonomiesRequest -from .types.policytagmanager import ListTaxonomiesResponse -from .types.policytagmanager import PolicyTag -from .types.policytagmanager import Taxonomy -from .types.policytagmanager import UpdatePolicyTagRequest -from .types.policytagmanager import UpdateTaxonomyRequest -from .types.policytagmanagerserialization import ExportTaxonomiesRequest -from .types.policytagmanagerserialization import ExportTaxonomiesResponse -from .types.policytagmanagerserialization import ImportTaxonomiesRequest -from .types.policytagmanagerserialization import ImportTaxonomiesResponse -from .types.policytagmanagerserialization import InlineSource -from .types.policytagmanagerserialization import SerializedPolicyTag -from .types.policytagmanagerserialization import SerializedTaxonomy -from .types.schema import ColumnSchema -from .types.schema import Schema -from .types.search import SearchCatalogResult -from .types.search import SearchResultType -from .types.table_spec import BigQueryDateShardedSpec -from .types.table_spec import BigQueryTableSpec -from .types.table_spec import TableSpec -from .types.table_spec import ViewSpec -from .types.table_spec import TableSourceType -from .types.tags import FieldType -from .types.tags import Tag -from .types.tags import TagField -from .types.tags import TagTemplate -from .types.tags import TagTemplateField -from .types.timestamps import SystemTimestamps - -__all__ = ( - 'DataCatalogAsyncClient', - 'PolicyTagManagerAsyncClient', - 'PolicyTagManagerSerializationAsyncClient', -'BigQueryDateShardedSpec', -'BigQueryTableSpec', -'ColumnSchema', -'CreateEntryGroupRequest', -'CreateEntryRequest', -'CreatePolicyTagRequest', -'CreateTagRequest', -'CreateTagTemplateFieldRequest', -'CreateTagTemplateRequest', -'CreateTaxonomyRequest', -'DataCatalogClient', -'DeleteEntryGroupRequest', -'DeleteEntryRequest', -'DeletePolicyTagRequest', -'DeleteTagRequest', -'DeleteTagTemplateFieldRequest', -'DeleteTagTemplateRequest', -'DeleteTaxonomyRequest', -'Entry', -'EntryGroup', -'EntryType', -'ExportTaxonomiesRequest', -'ExportTaxonomiesResponse', -'FieldType', -'GcsFileSpec', -'GcsFilesetSpec', -'GetEntryGroupRequest', -'GetEntryRequest', -'GetPolicyTagRequest', -'GetTagTemplateRequest', -'GetTaxonomyRequest', -'ImportTaxonomiesRequest', -'ImportTaxonomiesResponse', -'InlineSource', -'IntegratedSystem', -'ListEntriesRequest', -'ListEntriesResponse', -'ListEntryGroupsRequest', -'ListEntryGroupsResponse', -'ListPolicyTagsRequest', -'ListPolicyTagsResponse', -'ListTagsRequest', -'ListTagsResponse', -'ListTaxonomiesRequest', -'ListTaxonomiesResponse', -'LookupEntryRequest', -'PolicyTag', -'PolicyTagManagerClient', -'PolicyTagManagerSerializationClient', -'RenameTagTemplateFieldRequest', -'Schema', -'SearchCatalogRequest', -'SearchCatalogResponse', -'SearchCatalogResult', -'SearchResultType', -'SerializedPolicyTag', -'SerializedTaxonomy', -'SystemTimestamps', -'TableSourceType', -'TableSpec', -'Tag', -'TagField', -'TagTemplate', -'TagTemplateField', -'Taxonomy', -'UpdateEntryGroupRequest', -'UpdateEntryRequest', -'UpdatePolicyTagRequest', -'UpdateTagRequest', -'UpdateTagTemplateFieldRequest', -'UpdateTagTemplateRequest', -'UpdateTaxonomyRequest', -'ViewSpec', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json deleted file mode 100644 index 39950163..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,471 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.datacatalog_v1beta1", - "protoPackage": "google.cloud.datacatalog.v1beta1", - "schema": "1.0", - "services": { - "DataCatalog": { - "clients": { - "grpc": { - "libraryClient": "DataCatalogClient", - "rpcs": { - "CreateEntry": { - "methods": [ - "create_entry" - ] - }, - "CreateEntryGroup": { - "methods": [ - "create_entry_group" - ] - }, - "CreateTag": { - "methods": [ - "create_tag" - ] - }, - "CreateTagTemplate": { - "methods": [ - "create_tag_template" - ] - }, - "CreateTagTemplateField": { - "methods": [ - "create_tag_template_field" - ] - }, - "DeleteEntry": { - "methods": [ - "delete_entry" - ] - }, - "DeleteEntryGroup": { - "methods": [ - "delete_entry_group" - ] - }, - "DeleteTag": { - "methods": [ - "delete_tag" - ] - }, - "DeleteTagTemplate": { - "methods": [ - "delete_tag_template" - ] - }, - "DeleteTagTemplateField": { - "methods": [ - "delete_tag_template_field" - ] - }, - "GetEntry": { - "methods": [ - "get_entry" - ] - }, - "GetEntryGroup": { - "methods": [ - "get_entry_group" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagTemplate": { - "methods": [ - "get_tag_template" - ] - }, - "ListEntries": { - "methods": [ - "list_entries" - ] - }, - "ListEntryGroups": { - "methods": [ - "list_entry_groups" - ] - }, - "ListTags": { - "methods": [ - "list_tags" - ] - }, - "LookupEntry": { - "methods": [ - "lookup_entry" - ] - }, - "RenameTagTemplateField": { - "methods": [ - "rename_tag_template_field" - ] - }, - "SearchCatalog": { - "methods": [ - "search_catalog" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEntry": { - "methods": [ - "update_entry" - ] - }, - "UpdateEntryGroup": { - "methods": [ - "update_entry_group" - ] - }, - "UpdateTag": { - "methods": [ - "update_tag" - ] - }, - "UpdateTagTemplate": { - "methods": [ - "update_tag_template" - ] - }, - "UpdateTagTemplateField": { - "methods": [ - "update_tag_template_field" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataCatalogAsyncClient", - "rpcs": { - "CreateEntry": { - "methods": [ - "create_entry" - ] - }, - "CreateEntryGroup": { - "methods": [ - "create_entry_group" - ] - }, - "CreateTag": { - "methods": [ - "create_tag" - ] - }, - "CreateTagTemplate": { - "methods": [ - "create_tag_template" - ] - }, - "CreateTagTemplateField": { - "methods": [ - "create_tag_template_field" - ] - }, - "DeleteEntry": { - "methods": [ - "delete_entry" - ] - }, - "DeleteEntryGroup": { - "methods": [ - "delete_entry_group" - ] - }, - "DeleteTag": { - "methods": [ - "delete_tag" - ] - }, - "DeleteTagTemplate": { - "methods": [ - "delete_tag_template" - ] - }, - "DeleteTagTemplateField": { - "methods": [ - "delete_tag_template_field" - ] - }, - "GetEntry": { - "methods": [ - "get_entry" - ] - }, - "GetEntryGroup": { - "methods": [ - "get_entry_group" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagTemplate": { - "methods": [ - "get_tag_template" - ] - }, - "ListEntries": { - "methods": [ - "list_entries" - ] - }, - "ListEntryGroups": { - "methods": [ - "list_entry_groups" - ] - }, - "ListTags": { - "methods": [ - "list_tags" - ] - }, - "LookupEntry": { - "methods": [ - "lookup_entry" - ] - }, - "RenameTagTemplateField": { - "methods": [ - "rename_tag_template_field" - ] - }, - "SearchCatalog": { - "methods": [ - "search_catalog" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateEntry": { - "methods": [ - "update_entry" - ] - }, - "UpdateEntryGroup": { - "methods": [ - "update_entry_group" - ] - }, - "UpdateTag": { - "methods": [ - "update_tag" - ] - }, - "UpdateTagTemplate": { - "methods": [ - "update_tag_template" - ] - }, - "UpdateTagTemplateField": { - "methods": [ - "update_tag_template_field" - ] - } - } - } - } - }, - "PolicyTagManager": { - "clients": { - "grpc": { - "libraryClient": "PolicyTagManagerClient", - "rpcs": { - "CreatePolicyTag": { - "methods": [ - "create_policy_tag" - ] - }, - "CreateTaxonomy": { - "methods": [ - "create_taxonomy" - ] - }, - "DeletePolicyTag": { - "methods": [ - "delete_policy_tag" - ] - }, - "DeleteTaxonomy": { - "methods": [ - "delete_taxonomy" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetPolicyTag": { - "methods": [ - "get_policy_tag" - ] - }, - "GetTaxonomy": { - "methods": [ - "get_taxonomy" - ] - }, - "ListPolicyTags": { - "methods": [ - "list_policy_tags" - ] - }, - "ListTaxonomies": { - "methods": [ - "list_taxonomies" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdatePolicyTag": { - "methods": [ - "update_policy_tag" - ] - }, - "UpdateTaxonomy": { - "methods": [ - "update_taxonomy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PolicyTagManagerAsyncClient", - "rpcs": { - "CreatePolicyTag": { - "methods": [ - "create_policy_tag" - ] - }, - "CreateTaxonomy": { - "methods": [ - "create_taxonomy" - ] - }, - "DeletePolicyTag": { - "methods": [ - "delete_policy_tag" - ] - }, - "DeleteTaxonomy": { - "methods": [ - "delete_taxonomy" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetPolicyTag": { - "methods": [ - "get_policy_tag" - ] - }, - "GetTaxonomy": { - "methods": [ - "get_taxonomy" - ] - }, - "ListPolicyTags": { - "methods": [ - "list_policy_tags" - ] - }, - "ListTaxonomies": { - "methods": [ - "list_taxonomies" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdatePolicyTag": { - "methods": [ - "update_policy_tag" - ] - }, - "UpdateTaxonomy": { - "methods": [ - "update_taxonomy" - ] - } - } - } - } - }, - "PolicyTagManagerSerialization": { - "clients": { - "grpc": { - "libraryClient": "PolicyTagManagerSerializationClient", - "rpcs": { - "ExportTaxonomies": { - "methods": [ - "export_taxonomies" - ] - }, - "ImportTaxonomies": { - "methods": [ - "import_taxonomies" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PolicyTagManagerSerializationAsyncClient", - "rpcs": { - "ExportTaxonomies": { - "methods": [ - "export_taxonomies" - ] - }, - "ImportTaxonomies": { - "methods": [ - "import_taxonomies" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed deleted file mode 100644 index bb4088a3..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-datacatalog package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/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/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__init__.py deleted file mode 100644 index b45be1eb..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/__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 DataCatalogClient -from .async_client import DataCatalogAsyncClient - -__all__ = ( - 'DataCatalogClient', - 'DataCatalogAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py deleted file mode 100644 index bd522cea..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/async_client.py +++ /dev/null @@ -1,2878 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers -from google.cloud.datacatalog_v1beta1.types import common -from google.cloud.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1beta1.types import schema -from google.cloud.datacatalog_v1beta1.types import search -from google.cloud.datacatalog_v1beta1.types import table_spec -from google.cloud.datacatalog_v1beta1.types import tags -from google.cloud.datacatalog_v1beta1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport -from .client import DataCatalogClient - - -class DataCatalogAsyncClient: - """Data Catalog API service allows clients to discover, - understand, and manage their data. - """ - - _client: DataCatalogClient - - DEFAULT_ENDPOINT = DataCatalogClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DataCatalogClient.DEFAULT_MTLS_ENDPOINT - - entry_path = staticmethod(DataCatalogClient.entry_path) - parse_entry_path = staticmethod(DataCatalogClient.parse_entry_path) - entry_group_path = staticmethod(DataCatalogClient.entry_group_path) - parse_entry_group_path = staticmethod(DataCatalogClient.parse_entry_group_path) - tag_path = staticmethod(DataCatalogClient.tag_path) - parse_tag_path = staticmethod(DataCatalogClient.parse_tag_path) - tag_template_path = staticmethod(DataCatalogClient.tag_template_path) - parse_tag_template_path = staticmethod(DataCatalogClient.parse_tag_template_path) - tag_template_field_path = staticmethod(DataCatalogClient.tag_template_field_path) - parse_tag_template_field_path = staticmethod(DataCatalogClient.parse_tag_template_field_path) - common_billing_account_path = staticmethod(DataCatalogClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataCatalogClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DataCatalogClient.common_folder_path) - parse_common_folder_path = staticmethod(DataCatalogClient.parse_common_folder_path) - common_organization_path = staticmethod(DataCatalogClient.common_organization_path) - parse_common_organization_path = staticmethod(DataCatalogClient.parse_common_organization_path) - common_project_path = staticmethod(DataCatalogClient.common_project_path) - parse_common_project_path = staticmethod(DataCatalogClient.parse_common_project_path) - common_location_path = staticmethod(DataCatalogClient.common_location_path) - parse_common_location_path = staticmethod(DataCatalogClient.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: - DataCatalogAsyncClient: The constructed client. - """ - return DataCatalogClient.from_service_account_info.__func__(DataCatalogAsyncClient, 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: - DataCatalogAsyncClient: The constructed client. - """ - return DataCatalogClient.from_service_account_file.__func__(DataCatalogAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DataCatalogTransport: - """Returns the transport used by the client instance. - - Returns: - DataCatalogTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DataCatalogClient).get_transport_class, type(DataCatalogClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DataCatalogTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data catalog 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, ~.DataCatalogTransport]): 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 = DataCatalogClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search_catalog(self, - request: Union[datacatalog.SearchCatalogRequest, dict] = None, - *, - scope: datacatalog.SearchCatalogRequest.Scope = None, - query: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchCatalogAsyncPager: - r"""Searches Data Catalog for multiple resources like entries, tags - that match a query. - - This is a custom method - (https://cloud.google.com/apis/design/custom_methods) and does - not return the complete resource, only the resource identifier - and high level fields. Clients can subsequentally call ``Get`` - methods. - - Note that Data Catalog search queries do not guarantee full - recall. Query results that match your query may not be returned, - even in subsequent result pages. Also note that results returned - (and not returned) can vary across repeated search queries. - - See `Data Catalog Search - Syntax `__ - for more information. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest, dict]): - The request object. Request message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - scope (:class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope`): - Required. The scope of this search request. A ``scope`` - that has empty ``include_org_ids``, - ``include_project_ids`` AND false - ``include_gcp_public_datasets`` is considered invalid. - Data Catalog will return an error in such a case. - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Required. The query string in search query syntax. The - query must be non-empty. - - Query strings can be simple as "x" or more qualified as: - - - name:x - - column:x - - description:y - - Note: Query tokens need to have a minimum of 3 - characters for substring matching to work correctly. See - `Data Catalog Search - Syntax `__ - for more information. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.services.data_catalog.pagers.SearchCatalogAsyncPager: - Response message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - - 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([scope, query]) - if request is 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 = datacatalog.SearchCatalogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_catalog, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.SearchCatalogAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_entry_group(self, - request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, - *, - parent: str = None, - entry_group_id: str = None, - entry_group: datacatalog.EntryGroup = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""A maximum of 10,000 entry groups may be created per organization - across all locations. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryGroupRequest, dict]): - The request object. Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. - parent (:class:`str`): - Required. The name of the project this entry group is - in. Example: - - - projects/{project_id}/locations/{location} - - Note that this EntryGroup and its child resources may - not actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group_id (:class:`str`): - Required. The id of the entry group - to create. The id must begin with a - letter or underscore, contain only - English letters, numbers and - underscores, and be at most 64 - characters. - - This corresponds to the ``entry_group_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group (:class:`google.cloud.datacatalog_v1beta1.types.EntryGroup`): - The entry group to create. Defaults - to an empty entry group. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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, entry_group_id, entry_group]) - if request is 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 = datacatalog.CreateEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_group_id is not None: - request.entry_group_id = entry_group_id - if entry_group is not None: - request.entry_group = entry_group - - # 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_entry_group, - default_timeout=None, - client_info=DEFAULT_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_entry_group(self, - request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, - *, - entry_group: datacatalog.EntryGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Updates an EntryGroup. The user should enable the Data Catalog - API in the project identified by the ``entry_group.name`` - parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryGroupRequest, dict]): - The request object. Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. - entry_group (:class:`google.cloud.datacatalog_v1beta1.types.EntryGroup`): - Required. The updated entry group. - "name" field must be set. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update on the entry - group. If absent or empty, all - modifiable fields are updated. - - 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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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([entry_group, 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 = datacatalog.UpdateEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry_group is not None: - request.entry_group = entry_group - 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_entry_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry_group.name", request.entry_group.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_entry_group(self, - request: Union[datacatalog.GetEntryGroupRequest, dict] = None, - *, - name: str = None, - read_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Gets an EntryGroup. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryGroupRequest, dict]): - The request object. Request message for - [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. - name (:class:`str`): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - read_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to return. If not set or - empty, all fields are returned. - - This corresponds to the ``read_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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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, read_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 = datacatalog.GetEntryGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if read_mask is not None: - request.read_mask = read_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.get_entry_group, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entry_group(self, - request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an EntryGroup. Only entry groups that do not contain - entries can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryGroupRequest, dict]): - The request object. Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. - name (:class:`str`): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_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 = datacatalog.DeleteEntryGroupRequest(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_entry_group, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_entry_groups(self, - request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntryGroupsAsyncPager: - r"""Lists entry groups. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListEntryGroupsRequest, dict]): - The request object. Request message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - parent (:class:`str`): - Required. The name of the location that contains the - entry groups, which can be provided in URL format. - Example: - - - projects/{project_id}/locations/{location} - - 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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntryGroupsAsyncPager: - Response message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - - 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 = datacatalog.ListEntryGroupsRequest(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_entry_groups, - default_timeout=None, - client_info=DEFAULT_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.ListEntryGroupsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_entry(self, - request: Union[datacatalog.CreateEntryRequest, dict] = None, - *, - parent: str = None, - entry_id: str = None, - entry: datacatalog.Entry = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Creates an entry. Only entries of 'FILESET' type or - user-specified type can be created. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - A maximum of 100,000 entries may be created per entry group. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryRequest, dict]): - The request object. Request message for - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. - parent (:class:`str`): - Required. The name of the entry group this entry is in. - Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - Note that this Entry and its child resources may not - actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_id (:class:`str`): - Required. The id of the entry to - create. - - This corresponds to the ``entry_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry (:class:`google.cloud.datacatalog_v1beta1.types.Entry`): - Required. The entry to create. - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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, entry_id, entry]) - if request is 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 = datacatalog.CreateEntryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_id is not None: - request.entry_id = entry_id - if entry is not None: - request.entry = entry - - # 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_entry, - default_timeout=None, - client_info=DEFAULT_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_entry(self, - request: Union[datacatalog.UpdateEntryRequest, dict] = None, - *, - entry: datacatalog.Entry = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Updates an existing entry. Users should enable the Data Catalog - API in the project identified by the ``entry.name`` parameter - (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryRequest, dict]): - The request object. Request message for - [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. - entry (:class:`google.cloud.datacatalog_v1beta1.types.Entry`): - Required. The updated entry. The - "name" field must be set. - - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update on the entry. If absent or empty, - all modifiable fields are updated. - - The following fields are modifiable: - - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - - For entries with type ``FILESET`` - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - - For entries with ``user_specified_type`` - - - ``schema`` - - ``display_name`` - - ``description`` - - user_specified_type - - user_specified_system - - linked_resource - - source_system_timestamps - - 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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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([entry, 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 = datacatalog.UpdateEntryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry is not None: - request.entry = entry - 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_entry, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry.name", request.entry.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entry(self, - request: Union[datacatalog.DeleteEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing entry. Only entries created through - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] - method can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryRequest, dict]): - The request object. Request message for - [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. - name (:class:`str`): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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 = datacatalog.DeleteEntryRequest(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_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_entry(self, - request: Union[datacatalog.GetEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryRequest, dict]): - The request object. Request message for - [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. - name (:class:`str`): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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 = datacatalog.GetEntryRequest(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_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def lookup_entry(self, - request: Union[datacatalog.LookupEntryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Get an entry by target resource name. This method - allows clients to use the resource name from the source - Google Cloud Platform service to get the Data Catalog - Entry. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.LookupEntryRequest, dict]): - The request object. Request message for - [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # Create or coerce a protobuf request object. - request = datacatalog.LookupEntryRequest(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.lookup_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_entries(self, - request: Union[datacatalog.ListEntriesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntriesAsyncPager: - r"""Lists entries. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListEntriesRequest, dict]): - The request object. Request message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - parent (:class:`str`): - Required. The name of the entry group that contains the - entries, which can be provided in URL format. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntriesAsyncPager: - Response message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - - 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 = datacatalog.ListEntriesRequest(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_entries, - default_timeout=None, - client_info=DEFAULT_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.ListEntriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_tag_template(self, - request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, - *, - parent: str = None, - tag_template_id: str = None, - tag_template: tags.TagTemplate = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Creates a tag template. The user should enable the Data Catalog - API in the project identified by the ``parent`` parameter (see - `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateRequest, dict]): - The request object. Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. - parent (:class:`str`): - Required. The name of the project and the template - location - [region](https://cloud.google.com/data-catalog/docs/concepts/regions. - - Example: - - - projects/{project_id}/locations/us-central1 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_id (:class:`str`): - Required. The id of the tag template - to create. - - This corresponds to the ``tag_template_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplate`): - Required. The tag template to create. - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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, tag_template_id, tag_template]) - if request is 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 = datacatalog.CreateTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_id is not None: - request.tag_template_id = tag_template_id - if tag_template is not None: - request.tag_template = tag_template - - # 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_tag_template, - default_timeout=None, - client_info=DEFAULT_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_tag_template(self, - request: Union[datacatalog.GetTagTemplateRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Gets a tag template. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetTagTemplateRequest, dict]): - The request object. Request message for - [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. - name (:class:`str`): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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 = datacatalog.GetTagTemplateRequest(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_tag_template, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_tag_template(self, - request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, - *, - tag_template: tags.TagTemplate = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Updates a tag template. This method cannot be used to update the - fields of a template. The tag template fields are represented as - separate resources and should be updated using their own - create/update/delete methods. Users should enable the Data - Catalog API in the project identified by the - ``tag_template.name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateRequest, dict]): - The request object. Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. - tag_template (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplate`): - Required. The template to update. The - "name" field must be set. - - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The field mask specifies the parts of the template to - overwrite. - - Allowed fields: - - - ``display_name`` - - If absent or empty, all of the allowed fields above will - be updated. - - 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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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([tag_template, 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 = datacatalog.UpdateTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_template is not None: - request.tag_template = tag_template - 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_tag_template, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_template.name", request.tag_template.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_tag_template(self, - request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag template and all tags using the template. Users - should enable the Data Catalog API in the project identified by - the ``name`` parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateRequest, dict]): - The request object. Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. - name (:class:`str`): - Required. The name of the tag template to delete. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (:class:`bool`): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of any possible - tags using this template. ``force = false`` will be - supported in the future. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 = datacatalog.DeleteTagTemplateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # 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_tag_template, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_tag_template_field(self, - request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, - *, - parent: str = None, - tag_template_field_id: str = None, - tag_template_field: tags.TagTemplateField = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Creates a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``parent`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateFieldRequest, dict]): - The request object. Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. - parent (:class:`str`): - Required. The name of the project and the template - location - `region `__. - - Example: - - - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field_id (:class:`str`): - Required. The ID of the tag template field to create. - Field ids can contain letters (both uppercase and - lowercase), numbers (0-9), underscores (_) and dashes - (-). Field IDs must be at least 1 character long and at - most 128 characters long. Field IDs must also be unique - within their template. - - This corresponds to the ``tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplateField`): - Required. The tag template field to - create. - - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field_id, tag_template_field]) - if request is 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 = datacatalog.CreateTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_field_id is not None: - request.tag_template_field_id = tag_template_field_id - if tag_template_field is not None: - request.tag_template_field = tag_template_field - - # 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_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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_tag_template_field(self, - request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - tag_template_field: tags.TagTemplateField = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Updates a field in a tag template. This method cannot be used to - update the field type. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateFieldRequest, dict]): - The request object. Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. - name (:class:`str`): - Required. The name of the tag template field. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (:class:`google.cloud.datacatalog_v1beta1.types.TagTemplateField`): - Required. The template to update. - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. The field mask specifies the parts of the - template to be updated. Allowed fields: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If ``update_mask`` is not set or empty, all of the - allowed fields above will be updated. - - When updating an enum type, the provided values will be - merged with the existing values. Therefore, enum values - can only be added, existing enum values cannot be - deleted nor renamed. Updating a template field from - optional to required is NOT allowed. - - 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.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field, 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 = datacatalog.UpdateTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if tag_template_field is not None: - request.tag_template_field = tag_template_field - 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_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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 rename_tag_template_field(self, - request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - new_tag_template_field_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``name`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.RenameTagTemplateFieldRequest, dict]): - The request object. Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. - name (:class:`str`): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_tag_template_field_id (:class:`str`): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - - This corresponds to the ``new_tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_tag_template_field_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = datacatalog.RenameTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_tag_template_field_id is not None: - request.new_tag_template_field_id = new_tag_template_field_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.rename_tag_template_field, - default_timeout=None, - client_info=DEFAULT_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_tag_template_field(self, - request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a field in a tag template and all uses of that field. - Users should enable the Data Catalog API in the project - identified by the ``name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateFieldRequest, dict]): - The request object. Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. - name (:class:`str`): - Required. The name of the tag template field to delete. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (:class:`bool`): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of this field from - any tags using this field. ``force = false`` will be - supported in the future. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 = datacatalog.DeleteTagTemplateFieldRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # 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_tag_template_field, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def create_tag(self, - request: Union[datacatalog.CreateTagRequest, dict] = None, - *, - parent: str = None, - tag: tags.Tag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Creates a tag on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The - project identified by the ``parent`` parameter for the - `tag `__ - and the `tag - template `__ - used to create the tag must be from the same organization. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagRequest, dict]): - The request object. Request message for - [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. - parent (:class:`str`): - Required. The name of the resource to attach this tag - to. Tags can be attached to Entries. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - - Note that this Tag and its child resources may not - actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag (:class:`google.cloud.datacatalog_v1beta1.types.Tag`): - Required. The tag to create. - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Tag: - Tags are used to attach custom metadata to Data Catalog resources. Tags - conform to the specifications within their tag - template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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, tag]) - if request is 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 = datacatalog.CreateTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag is not None: - request.tag = tag - - # 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_tag, - default_timeout=None, - client_info=DEFAULT_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_tag(self, - request: Union[datacatalog.UpdateTagRequest, dict] = None, - *, - tag: tags.Tag = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Updates an existing tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagRequest, dict]): - The request object. Request message for - [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. - tag (:class:`google.cloud.datacatalog_v1beta1.types.Tag`): - Required. The updated tag. The "name" - field must be set. - - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update on the Tag. If absent or empty, all - modifiable fields are updated. Currently the only - modifiable field is the field ``fields``. - - 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.datacatalog_v1beta1.types.Tag: - Tags are used to attach custom metadata to Data Catalog resources. Tags - conform to the specifications within their tag - template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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([tag, 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 = datacatalog.UpdateTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag is not None: - request.tag = tag - 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_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag.name", request.tag.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_tag(self, - request: Union[datacatalog.DeleteTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagRequest, dict]): - The request object. Request message for - [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. - name (:class:`str`): - Required. The name of the tag to delete. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_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 = datacatalog.DeleteTagRequest(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_tag, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_tags(self, - request: Union[datacatalog.ListTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTagsAsyncPager: - r"""Lists the tags on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListTagsRequest, dict]): - The request object. Request message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - parent (:class:`str`): - Required. The name of the Data Catalog resource to list - the tags of. The resource could be an - [Entry][google.cloud.datacatalog.v1beta1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. - - Examples: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.services.data_catalog.pagers.ListTagsAsyncPager: - Response message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - - 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 = datacatalog.ListTagsRequest(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_tags, - 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=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListTagsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy for a resource. Replaces any - existing policy. Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entries.setIamPolicy`` to set policies on - entries. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. A ``NOT_FOUND`` - error is returned if the resource does not exist. An empty - policy is returned if the resource exists but does not have a - policy set on it. - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entries.getIamPolicy`` to get policies on - entries. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # 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_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the caller's permissions on a resource. If the resource - does not exist, an empty set of permissions is returned (We - don't return a ``NOT_FOUND`` error). - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - A caller is not required to have Google IAM permission to make - this request. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataCatalogAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py deleted file mode 100644 index 9adf67c4..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py +++ /dev/null @@ -1,3039 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers -from google.cloud.datacatalog_v1beta1.types import common -from google.cloud.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1beta1.types import schema -from google.cloud.datacatalog_v1beta1.types import search -from google.cloud.datacatalog_v1beta1.types import table_spec -from google.cloud.datacatalog_v1beta1.types import tags -from google.cloud.datacatalog_v1beta1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DataCatalogGrpcTransport -from .transports.grpc_asyncio import DataCatalogGrpcAsyncIOTransport - - -class DataCatalogClientMeta(type): - """Metaclass for the DataCatalog 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[DataCatalogTransport]] - _transport_registry["grpc"] = DataCatalogGrpcTransport - _transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DataCatalogTransport]: - """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 DataCatalogClient(metaclass=DataCatalogClientMeta): - """Data Catalog API service allows clients to discover, - understand, and manage their data. - """ - - @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 = "datacatalog.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: - DataCatalogClient: 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: - DataCatalogClient: 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) -> DataCatalogTransport: - """Returns the transport used by the client instance. - - Returns: - DataCatalogTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entry_path(project: str,location: str,entry_group: str,entry: str,) -> str: - """Returns a fully-qualified entry string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) - - @staticmethod - def parse_entry_path(path: str) -> Dict[str,str]: - """Parses a entry path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def entry_group_path(project: str,location: str,entry_group: str,) -> str: - """Returns a fully-qualified entry_group string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) - - @staticmethod - def parse_entry_group_path(path: str) -> Dict[str,str]: - """Parses a entry_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_path(project: str,location: str,entry_group: str,entry: str,tag: str,) -> str: - """Returns a fully-qualified tag string.""" - return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) - - @staticmethod - def parse_tag_path(path: str) -> Dict[str,str]: - """Parses a tag path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)/tags/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_template_path(project: str,location: str,tag_template: str,) -> str: - """Returns a fully-qualified tag_template string.""" - return "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) - - @staticmethod - def parse_tag_template_path(path: str) -> Dict[str,str]: - """Parses a tag_template path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def tag_template_field_path(project: str,location: str,tag_template: str,field: str,) -> str: - """Returns a fully-qualified tag_template_field string.""" - return "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) - - @staticmethod - def parse_tag_template_field_path(path: str) -> Dict[str,str]: - """Parses a tag_template_field path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/tagTemplates/(?P.+?)/fields/(?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, DataCatalogTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the data catalog 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, DataCatalogTransport]): 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, DataCatalogTransport): - # transport is a DataCatalogTransport 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=True, - ) - - def search_catalog(self, - request: Union[datacatalog.SearchCatalogRequest, dict] = None, - *, - scope: datacatalog.SearchCatalogRequest.Scope = None, - query: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchCatalogPager: - r"""Searches Data Catalog for multiple resources like entries, tags - that match a query. - - This is a custom method - (https://cloud.google.com/apis/design/custom_methods) and does - not return the complete resource, only the resource identifier - and high level fields. Clients can subsequentally call ``Get`` - methods. - - Note that Data Catalog search queries do not guarantee full - recall. Query results that match your query may not be returned, - even in subsequent result pages. Also note that results returned - (and not returned) can vary across repeated search queries. - - See `Data Catalog Search - Syntax `__ - for more information. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest, dict]): - The request object. Request message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - scope (google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope): - Required. The scope of this search request. A ``scope`` - that has empty ``include_org_ids``, - ``include_project_ids`` AND false - ``include_gcp_public_datasets`` is considered invalid. - Data Catalog will return an error in such a case. - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Required. The query string in search query syntax. The - query must be non-empty. - - Query strings can be simple as "x" or more qualified as: - - - name:x - - column:x - - description:y - - Note: Query tokens need to have a minimum of 3 - characters for substring matching to work correctly. See - `Data Catalog Search - Syntax `__ - for more information. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.services.data_catalog.pagers.SearchCatalogPager: - Response message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - - 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([scope, query]) - if request is 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 datacatalog.SearchCatalogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.SearchCatalogRequest): - request = datacatalog.SearchCatalogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_catalog] - - # 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.SearchCatalogPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_entry_group(self, - request: Union[datacatalog.CreateEntryGroupRequest, dict] = None, - *, - parent: str = None, - entry_group_id: str = None, - entry_group: datacatalog.EntryGroup = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""A maximum of 10,000 entry groups may be created per organization - across all locations. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryGroupRequest, dict]): - The request object. Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. - parent (str): - Required. The name of the project this entry group is - in. Example: - - - projects/{project_id}/locations/{location} - - Note that this EntryGroup and its child resources may - not actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group_id (str): - Required. The id of the entry group - to create. The id must begin with a - letter or underscore, contain only - English letters, numbers and - underscores, and be at most 64 - characters. - - This corresponds to the ``entry_group_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): - The entry group to create. Defaults - to an empty entry group. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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, entry_group_id, entry_group]) - if request is 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 datacatalog.CreateEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateEntryGroupRequest): - request = datacatalog.CreateEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_group_id is not None: - request.entry_group_id = entry_group_id - if entry_group is not None: - request.entry_group = entry_group - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entry_group] - - # 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_entry_group(self, - request: Union[datacatalog.UpdateEntryGroupRequest, dict] = None, - *, - entry_group: datacatalog.EntryGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Updates an EntryGroup. The user should enable the Data Catalog - API in the project identified by the ``entry_group.name`` - parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryGroupRequest, dict]): - The request object. Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. - entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): - Required. The updated entry group. - "name" field must be set. - - This corresponds to the ``entry_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the entry - group. If absent or empty, all - modifiable fields are updated. - - 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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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([entry_group, 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 datacatalog.UpdateEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateEntryGroupRequest): - request = datacatalog.UpdateEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry_group is not None: - request.entry_group = entry_group - 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_entry_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry_group.name", request.entry_group.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_entry_group(self, - request: Union[datacatalog.GetEntryGroupRequest, dict] = None, - *, - name: str = None, - read_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.EntryGroup: - r"""Gets an EntryGroup. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryGroupRequest, dict]): - The request object. Request message for - [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. - name (str): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return. If not set or - empty, all fields are returned. - - This corresponds to the ``read_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.datacatalog_v1beta1.types.EntryGroup: - EntryGroup Metadata. - An EntryGroup resource represents a logical grouping - of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] - resources. - - """ - # 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, read_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 datacatalog.GetEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetEntryGroupRequest): - request = datacatalog.GetEntryGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if read_mask is not None: - request.read_mask = read_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_entry_group] - - # Certain fields should be 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_entry_group(self, - request: Union[datacatalog.DeleteEntryGroupRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an EntryGroup. Only entry groups that do not contain - entries can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryGroupRequest, dict]): - The request object. Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. - name (str): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_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 datacatalog.DeleteEntryGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteEntryGroupRequest): - request = datacatalog.DeleteEntryGroupRequest(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_entry_group] - - # Certain fields should be 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_entry_groups(self, - request: Union[datacatalog.ListEntryGroupsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntryGroupsPager: - r"""Lists entry groups. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListEntryGroupsRequest, dict]): - The request object. Request message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - parent (str): - Required. The name of the location that contains the - entry groups, which can be provided in URL format. - Example: - - - projects/{project_id}/locations/{location} - - 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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntryGroupsPager: - Response message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - - 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 datacatalog.ListEntryGroupsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListEntryGroupsRequest): - request = datacatalog.ListEntryGroupsRequest(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_entry_groups] - - # 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.ListEntryGroupsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_entry(self, - request: Union[datacatalog.CreateEntryRequest, dict] = None, - *, - parent: str = None, - entry_id: str = None, - entry: datacatalog.Entry = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Creates an entry. Only entries of 'FILESET' type or - user-specified type can be created. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - A maximum of 100,000 entries may be created per entry group. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateEntryRequest, dict]): - The request object. Request message for - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. - parent (str): - Required. The name of the entry group this entry is in. - Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - Note that this Entry and its child resources may not - actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry_id (str): - Required. The id of the entry to - create. - - This corresponds to the ``entry_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entry (google.cloud.datacatalog_v1beta1.types.Entry): - Required. The entry to create. - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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, entry_id, entry]) - if request is 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 datacatalog.CreateEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateEntryRequest): - request = datacatalog.CreateEntryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entry_id is not None: - request.entry_id = entry_id - if entry is not None: - request.entry = entry - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entry] - - # 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_entry(self, - request: Union[datacatalog.UpdateEntryRequest, dict] = None, - *, - entry: datacatalog.Entry = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Updates an existing entry. Users should enable the Data Catalog - API in the project identified by the ``entry.name`` parameter - (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateEntryRequest, dict]): - The request object. Request message for - [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. - entry (google.cloud.datacatalog_v1beta1.types.Entry): - Required. The updated entry. The - "name" field must be set. - - This corresponds to the ``entry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the entry. If absent or empty, - all modifiable fields are updated. - - The following fields are modifiable: - - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - - For entries with type ``FILESET`` - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - - For entries with ``user_specified_type`` - - - ``schema`` - - ``display_name`` - - ``description`` - - user_specified_type - - user_specified_system - - linked_resource - - source_system_timestamps - - 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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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([entry, 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 datacatalog.UpdateEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateEntryRequest): - request = datacatalog.UpdateEntryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entry is not None: - request.entry = entry - 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_entry] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entry.name", request.entry.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_entry(self, - request: Union[datacatalog.DeleteEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing entry. Only entries created through - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] - method can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteEntryRequest, dict]): - The request object. Request message for - [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. - name (str): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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 datacatalog.DeleteEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteEntryRequest): - request = datacatalog.DeleteEntryRequest(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_entry] - - # Certain fields should be 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_entry(self, - request: Union[datacatalog.GetEntryRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Gets an entry. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetEntryRequest, dict]): - The request object. Request message for - [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. - name (str): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # 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 datacatalog.GetEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetEntryRequest): - request = datacatalog.GetEntryRequest(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_entry] - - # Certain fields should be 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 lookup_entry(self, - request: Union[datacatalog.LookupEntryRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> datacatalog.Entry: - r"""Get an entry by target resource name. This method - allows clients to use the resource name from the source - Google Cloud Platform service to get the Data Catalog - Entry. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.LookupEntryRequest, dict]): - The request object. Request message for - [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Entry: - Entry Metadata. - A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery - dataset or a Pub/Sub topic), or outside of Google - Cloud Platform. Clients can use the linked_resource - field in the Entry resource to refer to the original - resource ID of the source system. - - An Entry resource contains resource details, such as - its schema. An Entry can also be used to attach - flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a datacatalog.LookupEntryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.LookupEntryRequest): - request = datacatalog.LookupEntryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.lookup_entry] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_entries(self, - request: Union[datacatalog.ListEntriesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntriesPager: - r"""Lists entries. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListEntriesRequest, dict]): - The request object. Request message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - parent (str): - Required. The name of the entry group that contains the - entries, which can be provided in URL format. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_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.datacatalog_v1beta1.services.data_catalog.pagers.ListEntriesPager: - Response message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - - 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 datacatalog.ListEntriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListEntriesRequest): - request = datacatalog.ListEntriesRequest(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_entries] - - # 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.ListEntriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_tag_template(self, - request: Union[datacatalog.CreateTagTemplateRequest, dict] = None, - *, - parent: str = None, - tag_template_id: str = None, - tag_template: tags.TagTemplate = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Creates a tag template. The user should enable the Data Catalog - API in the project identified by the ``parent`` parameter (see - `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateRequest, dict]): - The request object. Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. - parent (str): - Required. The name of the project and the template - location - [region](https://cloud.google.com/data-catalog/docs/concepts/regions. - - Example: - - - projects/{project_id}/locations/us-central1 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_id (str): - Required. The id of the tag template - to create. - - This corresponds to the ``tag_template_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): - Required. The tag template to create. - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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, tag_template_id, tag_template]) - if request is 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 datacatalog.CreateTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagTemplateRequest): - request = datacatalog.CreateTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_id is not None: - request.tag_template_id = tag_template_id - if tag_template is not None: - request.tag_template = tag_template - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_template] - - # 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_tag_template(self, - request: Union[datacatalog.GetTagTemplateRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Gets a tag template. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetTagTemplateRequest, dict]): - The request object. Request message for - [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. - name (str): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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 datacatalog.GetTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.GetTagTemplateRequest): - request = datacatalog.GetTagTemplateRequest(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_tag_template] - - # Certain fields should be 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 update_tag_template(self, - request: Union[datacatalog.UpdateTagTemplateRequest, dict] = None, - *, - tag_template: tags.TagTemplate = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplate: - r"""Updates a tag template. This method cannot be used to update the - fields of a template. The tag template fields are represented as - separate resources and should be updated using their own - create/update/delete methods. Users should enable the Data - Catalog API in the project identified by the - ``tag_template.name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateRequest, dict]): - The request object. Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. - tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): - Required. The template to update. The - "name" field must be set. - - This corresponds to the ``tag_template`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The field mask specifies the parts of the template to - overwrite. - - Allowed fields: - - - ``display_name`` - - If absent or empty, all of the allowed fields above will - be updated. - - 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.datacatalog_v1beta1.types.TagTemplate: - A tag template defines a tag, which can have one or more typed fields. - The template is used to create and attach the tag to - GCP resources. [Tag template - roles](\ https://cloud.google.com/iam/docs/understanding-roles#data-catalog-roles) - provide permissions to create, edit, and use the - template. See, for example, the [TagTemplate - User](\ https://cloud.google.com/data-catalog/docs/how-to/template-user) - role, which includes permission to use the tag - template to tag resources. - - """ - # 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([tag_template, 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 datacatalog.UpdateTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagTemplateRequest): - request = datacatalog.UpdateTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_template is not None: - request.tag_template = tag_template - 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_tag_template] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_template.name", request.tag_template.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_tag_template(self, - request: Union[datacatalog.DeleteTagTemplateRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag template and all tags using the template. Users - should enable the Data Catalog API in the project identified by - the ``name`` parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateRequest, dict]): - The request object. Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. - name (str): - Required. The name of the tag template to delete. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (bool): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of any possible - tags using this template. ``force = false`` will be - supported in the future. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 datacatalog.DeleteTagTemplateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagTemplateRequest): - request = datacatalog.DeleteTagTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_template] - - # Certain fields should be 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 create_tag_template_field(self, - request: Union[datacatalog.CreateTagTemplateFieldRequest, dict] = None, - *, - parent: str = None, - tag_template_field_id: str = None, - tag_template_field: tags.TagTemplateField = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Creates a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``parent`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagTemplateFieldRequest, dict]): - The request object. Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. - parent (str): - Required. The name of the project and the template - location - `region `__. - - Example: - - - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field_id (str): - Required. The ID of the tag template field to create. - Field ids can contain letters (both uppercase and - lowercase), numbers (0-9), underscores (_) and dashes - (-). Field IDs must be at least 1 character long and at - most 128 characters long. Field IDs must also be unique - within their template. - - This corresponds to the ``tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): - Required. The tag template field to - create. - - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field_id, tag_template_field]) - if request is 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 datacatalog.CreateTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagTemplateFieldRequest): - request = datacatalog.CreateTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag_template_field_id is not None: - request.tag_template_field_id = tag_template_field_id - if tag_template_field is not None: - request.tag_template_field = tag_template_field - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_template_field] - - # 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_tag_template_field(self, - request: Union[datacatalog.UpdateTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - tag_template_field: tags.TagTemplateField = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Updates a field in a tag template. This method cannot be used to - update the field type. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagTemplateFieldRequest, dict]): - The request object. Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. - name (str): - Required. The name of the tag template field. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): - Required. The template to update. - This corresponds to the ``tag_template_field`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The field mask specifies the parts of the - template to be updated. Allowed fields: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If ``update_mask`` is not set or empty, all of the - allowed fields above will be updated. - - When updating an enum type, the provided values will be - merged with the existing values. Therefore, enum values - can only be added, existing enum values cannot be - deleted nor renamed. Updating a template field from - optional to required is NOT allowed. - - 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.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, tag_template_field, 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 datacatalog.UpdateTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagTemplateFieldRequest): - request = datacatalog.UpdateTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if tag_template_field is not None: - request.tag_template_field = tag_template_field - 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_tag_template_field] - - # Certain fields should be 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 rename_tag_template_field(self, - request: Union[datacatalog.RenameTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - new_tag_template_field_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.TagTemplateField: - r"""Renames a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``name`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.RenameTagTemplateFieldRequest, dict]): - The request object. Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. - name (str): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - new_tag_template_field_id (str): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - - This corresponds to the ``new_tag_template_field_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.datacatalog_v1beta1.types.TagTemplateField: - The template for an individual field - within a tag template. - - """ - # 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, new_tag_template_field_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a datacatalog.RenameTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.RenameTagTemplateFieldRequest): - request = datacatalog.RenameTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if new_tag_template_field_id is not None: - request.new_tag_template_field_id = new_tag_template_field_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rename_tag_template_field] - - # Certain fields should be 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_tag_template_field(self, - request: Union[datacatalog.DeleteTagTemplateFieldRequest, dict] = None, - *, - name: str = None, - force: bool = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a field in a tag template and all uses of that field. - Users should enable the Data Catalog API in the project - identified by the ``name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagTemplateFieldRequest, dict]): - The request object. Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. - name (str): - Required. The name of the tag template field to delete. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (bool): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of this field from - any tags using this field. ``force = false`` will be - supported in the future. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, force]) - if request is 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 datacatalog.DeleteTagTemplateFieldRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagTemplateFieldRequest): - request = datacatalog.DeleteTagTemplateFieldRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_template_field] - - # Certain fields should be 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 create_tag(self, - request: Union[datacatalog.CreateTagRequest, dict] = None, - *, - parent: str = None, - tag: tags.Tag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Creates a tag on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The - project identified by the ``parent`` parameter for the - `tag `__ - and the `tag - template `__ - used to create the tag must be from the same organization. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTagRequest, dict]): - The request object. Request message for - [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. - parent (str): - Required. The name of the resource to attach this tag - to. Tags can be attached to Entries. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - - Note that this Tag and its child resources may not - actually be stored in the location in this name. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - tag (google.cloud.datacatalog_v1beta1.types.Tag): - Required. The tag to create. - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Tag: - Tags are used to attach custom metadata to Data Catalog resources. Tags - conform to the specifications within their tag - template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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, tag]) - if request is 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 datacatalog.CreateTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.CreateTagRequest): - request = datacatalog.CreateTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if tag is not None: - request.tag = tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag] - - # 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_tag(self, - request: Union[datacatalog.UpdateTagRequest, dict] = None, - *, - tag: tags.Tag = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tags.Tag: - r"""Updates an existing tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTagRequest, dict]): - The request object. Request message for - [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. - tag (google.cloud.datacatalog_v1beta1.types.Tag): - Required. The updated tag. The "name" - field must be set. - - This corresponds to the ``tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the Tag. If absent or empty, all - modifiable fields are updated. Currently the only - modifiable field is the field ``fields``. - - 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.datacatalog_v1beta1.types.Tag: - Tags are used to attach custom metadata to Data Catalog resources. Tags - conform to the specifications within their tag - template. - - See [Data Catalog - IAM](\ https://cloud.google.com/data-catalog/docs/concepts/iam) - for information on the permissions needed to create - or view tags. - - """ - # 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([tag, 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 datacatalog.UpdateTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.UpdateTagRequest): - request = datacatalog.UpdateTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag is not None: - request.tag = tag - 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_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag.name", request.tag.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_tag(self, - request: Union[datacatalog.DeleteTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTagRequest, dict]): - The request object. Request message for - [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. - name (str): - Required. The name of the tag to delete. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_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 datacatalog.DeleteTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.DeleteTagRequest): - request = datacatalog.DeleteTagRequest(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_tag] - - # Certain fields should be 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_tags(self, - request: Union[datacatalog.ListTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTagsPager: - r"""Lists the tags on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListTagsRequest, dict]): - The request object. Request message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - parent (str): - Required. The name of the Data Catalog resource to list - the tags of. The resource could be an - [Entry][google.cloud.datacatalog.v1beta1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. - - Examples: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_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.datacatalog_v1beta1.services.data_catalog.pagers.ListTagsPager: - Response message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - - 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 datacatalog.ListTagsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, datacatalog.ListTagsRequest): - request = datacatalog.ListTagsRequest(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_tags] - - # 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.ListTagsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy for a resource. Replaces any - existing policy. Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entries.setIamPolicy`` to set policies on - entries. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - resource: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. A ``NOT_FOUND`` - error is returned if the resource does not exist. An empty - policy is returned if the resource exists but does not have a - policy set on it. - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entries.getIamPolicy`` to get policies on - entries. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # 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([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the caller's permissions on a resource. If the resource - does not exist, an empty set of permissions is returned (We - don't return a ``NOT_FOUND`` error). - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - A caller is not required to have Google IAM permission to make - this request. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DataCatalogClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py deleted file mode 100644 index d53b511a..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/pagers.py +++ /dev/null @@ -1,508 +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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import search -from google.cloud.datacatalog_v1beta1.types import tags - - -class SearchCatalogPager: - """A pager for iterating through ``search_catalog`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchCatalog`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` - 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[..., datacatalog.SearchCatalogResponse], - request: datacatalog.SearchCatalogRequest, - response: datacatalog.SearchCatalogResponse, - *, - 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.datacatalog_v1beta1.types.SearchCatalogRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse): - 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 = datacatalog.SearchCatalogRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.SearchCatalogResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search.SearchCatalogResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchCatalogAsyncPager: - """A pager for iterating through ``search_catalog`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchCatalog`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse` - 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[datacatalog.SearchCatalogResponse]], - request: datacatalog.SearchCatalogRequest, - response: datacatalog.SearchCatalogResponse, - *, - 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.datacatalog_v1beta1.types.SearchCatalogRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.SearchCatalogResponse): - 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 = datacatalog.SearchCatalogRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.SearchCatalogResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[search.SearchCatalogResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntryGroupsPager: - """A pager for iterating through ``list_entry_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entry_groups`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntryGroups`` requests and continue to iterate - through the ``entry_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` - 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[..., datacatalog.ListEntryGroupsResponse], - request: datacatalog.ListEntryGroupsRequest, - response: datacatalog.ListEntryGroupsResponse, - *, - 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.datacatalog_v1beta1.types.ListEntryGroupsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse): - 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 = datacatalog.ListEntryGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListEntryGroupsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[datacatalog.EntryGroup]: - for page in self.pages: - yield from page.entry_groups - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntryGroupsAsyncPager: - """A pager for iterating through ``list_entry_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entry_groups`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntryGroups`` requests and continue to iterate - through the ``entry_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse` - 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[datacatalog.ListEntryGroupsResponse]], - request: datacatalog.ListEntryGroupsRequest, - response: datacatalog.ListEntryGroupsResponse, - *, - 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.datacatalog_v1beta1.types.ListEntryGroupsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListEntryGroupsResponse): - 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 = datacatalog.ListEntryGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListEntryGroupsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[datacatalog.EntryGroup]: - async def async_generator(): - async for page in self.pages: - for response in page.entry_groups: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntriesPager: - """A pager for iterating through ``list_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` - 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[..., datacatalog.ListEntriesResponse], - request: datacatalog.ListEntriesRequest, - response: datacatalog.ListEntriesResponse, - *, - 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.datacatalog_v1beta1.types.ListEntriesRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListEntriesResponse): - 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 = datacatalog.ListEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListEntriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[datacatalog.Entry]: - for page in self.pages: - yield from page.entries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntriesAsyncPager: - """A pager for iterating through ``list_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListEntriesResponse` - 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[datacatalog.ListEntriesResponse]], - request: datacatalog.ListEntriesRequest, - response: datacatalog.ListEntriesResponse, - *, - 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.datacatalog_v1beta1.types.ListEntriesRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListEntriesResponse): - 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 = datacatalog.ListEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListEntriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[datacatalog.Entry]: - async def async_generator(): - async for page in self.pages: - for response in page.entries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagsPager: - """A pager for iterating through ``list_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tags`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTags`` requests and continue to iterate - through the ``tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` - 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[..., datacatalog.ListTagsResponse], - request: datacatalog.ListTagsRequest, - response: datacatalog.ListTagsResponse, - *, - 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.datacatalog_v1beta1.types.ListTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListTagsResponse): - 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 = datacatalog.ListTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[datacatalog.ListTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tags.Tag]: - for page in self.pages: - yield from page.tags - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagsAsyncPager: - """A pager for iterating through ``list_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tags`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTags`` requests and continue to iterate - through the ``tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTagsResponse` - 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[datacatalog.ListTagsResponse]], - request: datacatalog.ListTagsRequest, - response: datacatalog.ListTagsResponse, - *, - 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.datacatalog_v1beta1.types.ListTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListTagsResponse): - 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 = datacatalog.ListTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[datacatalog.ListTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[tags.Tag]: - async def async_generator(): - async for page in self.pages: - for response in page.tags: - 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/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/__init__.py deleted file mode 100644 index f8baae0c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/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 DataCatalogTransport -from .grpc import DataCatalogGrpcTransport -from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]] -_transport_registry['grpc'] = DataCatalogGrpcTransport -_transport_registry['grpc_asyncio'] = DataCatalogGrpcAsyncIOTransport - -__all__ = ( - 'DataCatalogTransport', - 'DataCatalogGrpcTransport', - 'DataCatalogGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py deleted file mode 100644 index 6513efdd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/base.py +++ /dev/null @@ -1,584 +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 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.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -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-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class DataCatalogTransport(abc.ABC): - """Abstract transport class for DataCatalog.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search_catalog: gapic_v1.method.wrap_method( - self.search_catalog, - default_timeout=None, - client_info=client_info, - ), - self.create_entry_group: gapic_v1.method.wrap_method( - self.create_entry_group, - default_timeout=None, - client_info=client_info, - ), - self.update_entry_group: gapic_v1.method.wrap_method( - self.update_entry_group, - default_timeout=None, - client_info=client_info, - ), - self.get_entry_group: gapic_v1.method.wrap_method( - self.get_entry_group, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_entry_group: gapic_v1.method.wrap_method( - self.delete_entry_group, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_entry_groups: gapic_v1.method.wrap_method( - self.list_entry_groups, - default_timeout=None, - client_info=client_info, - ), - self.create_entry: gapic_v1.method.wrap_method( - self.create_entry, - default_timeout=None, - client_info=client_info, - ), - self.update_entry: gapic_v1.method.wrap_method( - self.update_entry, - default_timeout=None, - client_info=client_info, - ), - self.delete_entry: gapic_v1.method.wrap_method( - self.delete_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_entry: gapic_v1.method.wrap_method( - self.get_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.lookup_entry: gapic_v1.method.wrap_method( - self.lookup_entry, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_entries: gapic_v1.method.wrap_method( - self.list_entries, - default_timeout=None, - client_info=client_info, - ), - self.create_tag_template: gapic_v1.method.wrap_method( - self.create_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.get_tag_template: gapic_v1.method.wrap_method( - self.get_tag_template, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_tag_template: gapic_v1.method.wrap_method( - self.update_tag_template, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag_template: gapic_v1.method.wrap_method( - self.delete_tag_template, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag_template_field: gapic_v1.method.wrap_method( - self.create_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.update_tag_template_field: gapic_v1.method.wrap_method( - self.update_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.rename_tag_template_field: gapic_v1.method.wrap_method( - self.rename_tag_template_field, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag_template_field: gapic_v1.method.wrap_method( - self.delete_tag_template_field, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag: gapic_v1.method.wrap_method( - self.create_tag, - default_timeout=None, - client_info=client_info, - ), - self.update_tag: gapic_v1.method.wrap_method( - self.update_tag, - default_timeout=None, - client_info=client_info, - ), - self.delete_tag: gapic_v1.method.wrap_method( - self.delete_tag, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_tags: gapic_v1.method.wrap_method( - self.list_tags, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - Union[ - datacatalog.SearchCatalogResponse, - Awaitable[datacatalog.SearchCatalogResponse] - ]]: - raise NotImplementedError() - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - Union[ - datacatalog.EntryGroup, - Awaitable[datacatalog.EntryGroup] - ]]: - raise NotImplementedError() - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - Union[ - datacatalog.ListEntryGroupsResponse, - Awaitable[datacatalog.ListEntryGroupsResponse] - ]]: - raise NotImplementedError() - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - Union[ - datacatalog.Entry, - Awaitable[datacatalog.Entry] - ]]: - raise NotImplementedError() - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - Union[ - datacatalog.ListEntriesResponse, - Awaitable[datacatalog.ListEntriesResponse] - ]]: - raise NotImplementedError() - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - Union[ - tags.TagTemplate, - Awaitable[tags.TagTemplate] - ]]: - raise NotImplementedError() - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - Union[ - tags.TagTemplateField, - Awaitable[tags.TagTemplateField] - ]]: - raise NotImplementedError() - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - Union[ - tags.Tag, - Awaitable[tags.Tag] - ]]: - raise NotImplementedError() - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - Union[ - tags.Tag, - Awaitable[tags.Tag] - ]]: - raise NotImplementedError() - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - Union[ - datacatalog.ListTagsResponse, - Awaitable[datacatalog.ListTagsResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DataCatalogTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py deleted file mode 100644 index 24ce3010..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc.py +++ /dev/null @@ -1,1079 +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.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO - - -class DataCatalogGrpcTransport(DataCatalogTransport): - """gRPC backend transport for DataCatalog. - - Data Catalog API service allows clients to discover, - understand, and manage their data. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - datacatalog.SearchCatalogResponse]: - r"""Return a callable for the search catalog method over gRPC. - - Searches Data Catalog for multiple resources like entries, tags - that match a query. - - This is a custom method - (https://cloud.google.com/apis/design/custom_methods) and does - not return the complete resource, only the resource identifier - and high level fields. Clients can subsequentally call ``Get`` - methods. - - Note that Data Catalog search queries do not guarantee full - recall. Query results that match your query may not be returned, - even in subsequent result pages. Also note that results returned - (and not returned) can vary across repeated search queries. - - See `Data Catalog Search - Syntax `__ - for more information. - - Returns: - Callable[[~.SearchCatalogRequest], - ~.SearchCatalogResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_catalog' not in self._stubs: - self._stubs['search_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/SearchCatalog', - request_serializer=datacatalog.SearchCatalogRequest.serialize, - response_deserializer=datacatalog.SearchCatalogResponse.deserialize, - ) - return self._stubs['search_catalog'] - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the create entry group method over gRPC. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.CreateEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntryGroup', - request_serializer=datacatalog.CreateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['create_entry_group'] - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the update entry group method over gRPC. - - Updates an EntryGroup. The user should enable the Data Catalog - API in the project identified by the ``entry_group.name`` - parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntryGroup', - request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['update_entry_group'] - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - datacatalog.EntryGroup]: - r"""Return a callable for the get entry group method over gRPC. - - Gets an EntryGroup. - - Returns: - Callable[[~.GetEntryGroupRequest], - ~.EntryGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntryGroup', - request_serializer=datacatalog.GetEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['get_entry_group'] - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entry group method over gRPC. - - Deletes an EntryGroup. Only entry groups that do not contain - entries can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteEntryGroupRequest], - ~.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_entry_group' not in self._stubs: - self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntryGroup', - request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry_group'] - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - datacatalog.ListEntryGroupsResponse]: - r"""Return a callable for the list entry groups method over gRPC. - - Lists entry groups. - - Returns: - Callable[[~.ListEntryGroupsRequest], - ~.ListEntryGroupsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: - self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntryGroups', - request_serializer=datacatalog.ListEntryGroupsRequest.serialize, - response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, - ) - return self._stubs['list_entry_groups'] - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the create entry method over gRPC. - - Creates an entry. Only entries of 'FILESET' type or - user-specified type can be created. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - A maximum of 100,000 entries may be created per entry group. - - Returns: - Callable[[~.CreateEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['create_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntry', - request_serializer=datacatalog.CreateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['create_entry'] - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the update entry method over gRPC. - - Updates an existing entry. Users should enable the Data Catalog - API in the project identified by the ``entry.name`` parameter - (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['update_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntry', - request_serializer=datacatalog.UpdateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['update_entry'] - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entry method over gRPC. - - Deletes an existing entry. Only entries created through - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] - method can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteEntryRequest], - ~.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_entry' not in self._stubs: - self._stubs['delete_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntry', - request_serializer=datacatalog.DeleteEntryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry'] - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the get entry method over gRPC. - - Gets an entry. - - Returns: - Callable[[~.GetEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['get_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntry', - request_serializer=datacatalog.GetEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['get_entry'] - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - datacatalog.Entry]: - r"""Return a callable for the lookup entry method over gRPC. - - Get an entry by target resource name. This method - allows clients to use the resource name from the source - Google Cloud Platform service to get the Data Catalog - Entry. - - Returns: - Callable[[~.LookupEntryRequest], - ~.Entry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_entry' not in self._stubs: - self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/LookupEntry', - request_serializer=datacatalog.LookupEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['lookup_entry'] - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - datacatalog.ListEntriesResponse]: - r"""Return a callable for the list entries method over gRPC. - - Lists entries. - - Returns: - Callable[[~.ListEntriesRequest], - ~.ListEntriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entries' not in self._stubs: - self._stubs['list_entries'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntries', - request_serializer=datacatalog.ListEntriesRequest.serialize, - response_deserializer=datacatalog.ListEntriesResponse.deserialize, - ) - return self._stubs['list_entries'] - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the create tag template method over gRPC. - - Creates a tag template. The user should enable the Data Catalog - API in the project identified by the ``parent`` parameter (see - `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.CreateTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplate', - request_serializer=datacatalog.CreateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['create_tag_template'] - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the get tag template method over gRPC. - - Gets a tag template. - - Returns: - Callable[[~.GetTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetTagTemplate', - request_serializer=datacatalog.GetTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['get_tag_template'] - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - tags.TagTemplate]: - r"""Return a callable for the update tag template method over gRPC. - - Updates a tag template. This method cannot be used to update the - fields of a template. The tag template fields are represented as - separate resources and should be updated using their own - create/update/delete methods. Users should enable the Data - Catalog API in the project identified by the - ``tag_template.name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateTagTemplateRequest], - ~.TagTemplate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplate', - request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['update_tag_template'] - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag template method over gRPC. - - Deletes a tag template and all tags using the template. Users - should enable the Data Catalog API in the project identified by - the ``name`` parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteTagTemplateRequest], - ~.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_tag_template' not in self._stubs: - self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplate', - request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template'] - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the create tag template field method over gRPC. - - Creates a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``parent`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.CreateTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplateField', - request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['create_tag_template_field'] - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the update tag template field method over gRPC. - - Updates a field in a tag template. This method cannot be used to - update the field type. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplateField', - request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['update_tag_template_field'] - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - tags.TagTemplateField]: - r"""Return a callable for the rename tag template field method over gRPC. - - Renames a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``name`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.RenameTagTemplateFieldRequest], - ~.TagTemplateField]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field' not in self._stubs: - self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/RenameTagTemplateField', - request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field'] - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag template field method over gRPC. - - Deletes a field in a tag template and all uses of that field. - Users should enable the Data Catalog API in the project - identified by the ``name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteTagTemplateFieldRequest], - ~.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_tag_template_field' not in self._stubs: - self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplateField', - request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template_field'] - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - tags.Tag]: - r"""Return a callable for the create tag method over gRPC. - - Creates a tag on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The - project identified by the ``parent`` parameter for the - `tag `__ - and the `tag - template `__ - used to create the tag must be from the same organization. - - Returns: - Callable[[~.CreateTagRequest], - ~.Tag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['create_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTag', - request_serializer=datacatalog.CreateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['create_tag'] - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - tags.Tag]: - r"""Return a callable for the update tag method over gRPC. - - Updates an existing tag. - - Returns: - Callable[[~.UpdateTagRequest], - ~.Tag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['update_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTag', - request_serializer=datacatalog.UpdateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['update_tag'] - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete tag method over gRPC. - - Deletes a tag. - - Returns: - Callable[[~.DeleteTagRequest], - ~.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_tag' not in self._stubs: - self._stubs['delete_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTag', - request_serializer=datacatalog.DeleteTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag'] - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - datacatalog.ListTagsResponse]: - r"""Return a callable for the list tags method over gRPC. - - Lists the tags on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. - - Returns: - Callable[[~.ListTagsRequest], - ~.ListTagsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tags' not in self._stubs: - self._stubs['list_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListTags', - request_serializer=datacatalog.ListTagsRequest.serialize, - response_deserializer=datacatalog.ListTagsResponse.deserialize, - ) - return self._stubs['list_tags'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy for a resource. Replaces any - existing policy. Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entries.setIamPolicy`` to set policies on - entries. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. A ``NOT_FOUND`` - error is returned if the resource does not exist. An empty - policy is returned if the resource exists but does not have a - policy set on it. - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entries.getIamPolicy`` to get policies on - entries. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the caller's permissions on a resource. If the resource - does not exist, an empty set of permissions is returned (We - don't return a ``NOT_FOUND`` error). - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - A caller is not required to have Google IAM permission to make - this request. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'DataCatalogGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py deleted file mode 100644 index bc9a0d03..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/data_catalog/transports/grpc_asyncio.py +++ /dev/null @@ -1,1083 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import tags -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DataCatalogTransport, DEFAULT_CLIENT_INFO -from .grpc import DataCatalogGrpcTransport - - -class DataCatalogGrpcAsyncIOTransport(DataCatalogTransport): - """gRPC AsyncIO backend transport for DataCatalog. - - Data Catalog API service allows clients to discover, - understand, and manage their data. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 search_catalog(self) -> Callable[ - [datacatalog.SearchCatalogRequest], - Awaitable[datacatalog.SearchCatalogResponse]]: - r"""Return a callable for the search catalog method over gRPC. - - Searches Data Catalog for multiple resources like entries, tags - that match a query. - - This is a custom method - (https://cloud.google.com/apis/design/custom_methods) and does - not return the complete resource, only the resource identifier - and high level fields. Clients can subsequentally call ``Get`` - methods. - - Note that Data Catalog search queries do not guarantee full - recall. Query results that match your query may not be returned, - even in subsequent result pages. Also note that results returned - (and not returned) can vary across repeated search queries. - - See `Data Catalog Search - Syntax `__ - for more information. - - Returns: - Callable[[~.SearchCatalogRequest], - Awaitable[~.SearchCatalogResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_catalog' not in self._stubs: - self._stubs['search_catalog'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/SearchCatalog', - request_serializer=datacatalog.SearchCatalogRequest.serialize, - response_deserializer=datacatalog.SearchCatalogResponse.deserialize, - ) - return self._stubs['search_catalog'] - - @property - def create_entry_group(self) -> Callable[ - [datacatalog.CreateEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the create entry group method over gRPC. - - A maximum of 10,000 entry groups may be created per organization - across all locations. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.CreateEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['create_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntryGroup', - request_serializer=datacatalog.CreateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['create_entry_group'] - - @property - def update_entry_group(self) -> Callable[ - [datacatalog.UpdateEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the update entry group method over gRPC. - - Updates an EntryGroup. The user should enable the Data Catalog - API in the project identified by the ``entry_group.name`` - parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['update_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntryGroup', - request_serializer=datacatalog.UpdateEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['update_entry_group'] - - @property - def get_entry_group(self) -> Callable[ - [datacatalog.GetEntryGroupRequest], - Awaitable[datacatalog.EntryGroup]]: - r"""Return a callable for the get entry group method over gRPC. - - Gets an EntryGroup. - - Returns: - Callable[[~.GetEntryGroupRequest], - Awaitable[~.EntryGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_group' not in self._stubs: - self._stubs['get_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntryGroup', - request_serializer=datacatalog.GetEntryGroupRequest.serialize, - response_deserializer=datacatalog.EntryGroup.deserialize, - ) - return self._stubs['get_entry_group'] - - @property - def delete_entry_group(self) -> Callable[ - [datacatalog.DeleteEntryGroupRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete entry group method over gRPC. - - Deletes an EntryGroup. Only entry groups that do not contain - entries can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteEntryGroupRequest], - 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_entry_group' not in self._stubs: - self._stubs['delete_entry_group'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntryGroup', - request_serializer=datacatalog.DeleteEntryGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry_group'] - - @property - def list_entry_groups(self) -> Callable[ - [datacatalog.ListEntryGroupsRequest], - Awaitable[datacatalog.ListEntryGroupsResponse]]: - r"""Return a callable for the list entry groups method over gRPC. - - Lists entry groups. - - Returns: - Callable[[~.ListEntryGroupsRequest], - Awaitable[~.ListEntryGroupsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry_groups' not in self._stubs: - self._stubs['list_entry_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntryGroups', - request_serializer=datacatalog.ListEntryGroupsRequest.serialize, - response_deserializer=datacatalog.ListEntryGroupsResponse.deserialize, - ) - return self._stubs['list_entry_groups'] - - @property - def create_entry(self) -> Callable[ - [datacatalog.CreateEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the create entry method over gRPC. - - Creates an entry. Only entries of 'FILESET' type or - user-specified type can be created. - - Users should enable the Data Catalog API in the project - identified by the ``parent`` parameter (see [Data Catalog - Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - A maximum of 100,000 entries may be created per entry group. - - Returns: - Callable[[~.CreateEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['create_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateEntry', - request_serializer=datacatalog.CreateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['create_entry'] - - @property - def update_entry(self) -> Callable[ - [datacatalog.UpdateEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the update entry method over gRPC. - - Updates an existing entry. Users should enable the Data Catalog - API in the project identified by the ``entry.name`` parameter - (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['update_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateEntry', - request_serializer=datacatalog.UpdateEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['update_entry'] - - @property - def delete_entry(self) -> Callable[ - [datacatalog.DeleteEntryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete entry method over gRPC. - - Deletes an existing entry. Only entries created through - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry] - method can be deleted. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteEntryRequest], - 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_entry' not in self._stubs: - self._stubs['delete_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteEntry', - request_serializer=datacatalog.DeleteEntryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entry'] - - @property - def get_entry(self) -> Callable[ - [datacatalog.GetEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the get entry method over gRPC. - - Gets an entry. - - Returns: - Callable[[~.GetEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entry' not in self._stubs: - self._stubs['get_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetEntry', - request_serializer=datacatalog.GetEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['get_entry'] - - @property - def lookup_entry(self) -> Callable[ - [datacatalog.LookupEntryRequest], - Awaitable[datacatalog.Entry]]: - r"""Return a callable for the lookup entry method over gRPC. - - Get an entry by target resource name. This method - allows clients to use the resource name from the source - Google Cloud Platform service to get the Data Catalog - Entry. - - Returns: - Callable[[~.LookupEntryRequest], - Awaitable[~.Entry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_entry' not in self._stubs: - self._stubs['lookup_entry'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/LookupEntry', - request_serializer=datacatalog.LookupEntryRequest.serialize, - response_deserializer=datacatalog.Entry.deserialize, - ) - return self._stubs['lookup_entry'] - - @property - def list_entries(self) -> Callable[ - [datacatalog.ListEntriesRequest], - Awaitable[datacatalog.ListEntriesResponse]]: - r"""Return a callable for the list entries method over gRPC. - - Lists entries. - - Returns: - Callable[[~.ListEntriesRequest], - Awaitable[~.ListEntriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_entries' not in self._stubs: - self._stubs['list_entries'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListEntries', - request_serializer=datacatalog.ListEntriesRequest.serialize, - response_deserializer=datacatalog.ListEntriesResponse.deserialize, - ) - return self._stubs['list_entries'] - - @property - def create_tag_template(self) -> Callable[ - [datacatalog.CreateTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the create tag template method over gRPC. - - Creates a tag template. The user should enable the Data Catalog - API in the project identified by the ``parent`` parameter (see - `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.CreateTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['create_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplate', - request_serializer=datacatalog.CreateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['create_tag_template'] - - @property - def get_tag_template(self) -> Callable[ - [datacatalog.GetTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the get tag template method over gRPC. - - Gets a tag template. - - Returns: - Callable[[~.GetTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['get_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetTagTemplate', - request_serializer=datacatalog.GetTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['get_tag_template'] - - @property - def update_tag_template(self) -> Callable[ - [datacatalog.UpdateTagTemplateRequest], - Awaitable[tags.TagTemplate]]: - r"""Return a callable for the update tag template method over gRPC. - - Updates a tag template. This method cannot be used to update the - fields of a template. The tag template fields are represented as - separate resources and should be updated using their own - create/update/delete methods. Users should enable the Data - Catalog API in the project identified by the - ``tag_template.name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateTagTemplateRequest], - Awaitable[~.TagTemplate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template' not in self._stubs: - self._stubs['update_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplate', - request_serializer=datacatalog.UpdateTagTemplateRequest.serialize, - response_deserializer=tags.TagTemplate.deserialize, - ) - return self._stubs['update_tag_template'] - - @property - def delete_tag_template(self) -> Callable[ - [datacatalog.DeleteTagTemplateRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag template method over gRPC. - - Deletes a tag template and all tags using the template. Users - should enable the Data Catalog API in the project identified by - the ``name`` parameter (see [Data Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteTagTemplateRequest], - 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_tag_template' not in self._stubs: - self._stubs['delete_tag_template'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplate', - request_serializer=datacatalog.DeleteTagTemplateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template'] - - @property - def create_tag_template_field(self) -> Callable[ - [datacatalog.CreateTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the create tag template field method over gRPC. - - Creates a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``parent`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.CreateTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['create_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTagTemplateField', - request_serializer=datacatalog.CreateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['create_tag_template_field'] - - @property - def update_tag_template_field(self) -> Callable[ - [datacatalog.UpdateTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the update tag template field method over gRPC. - - Updates a field in a tag template. This method cannot be used to - update the field type. Users should enable the Data Catalog API - in the project identified by the ``name`` parameter (see [Data - Catalog Resource Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.UpdateTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_template_field' not in self._stubs: - self._stubs['update_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTagTemplateField', - request_serializer=datacatalog.UpdateTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['update_tag_template_field'] - - @property - def rename_tag_template_field(self) -> Callable[ - [datacatalog.RenameTagTemplateFieldRequest], - Awaitable[tags.TagTemplateField]]: - r"""Return a callable for the rename tag template field method over gRPC. - - Renames a field in a tag template. The user should enable the - Data Catalog API in the project identified by the ``name`` - parameter (see `Data Catalog Resource - Project `__ - for more information). - - Returns: - Callable[[~.RenameTagTemplateFieldRequest], - Awaitable[~.TagTemplateField]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'rename_tag_template_field' not in self._stubs: - self._stubs['rename_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/RenameTagTemplateField', - request_serializer=datacatalog.RenameTagTemplateFieldRequest.serialize, - response_deserializer=tags.TagTemplateField.deserialize, - ) - return self._stubs['rename_tag_template_field'] - - @property - def delete_tag_template_field(self) -> Callable[ - [datacatalog.DeleteTagTemplateFieldRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag template field method over gRPC. - - Deletes a field in a tag template and all uses of that field. - Users should enable the Data Catalog API in the project - identified by the ``name`` parameter (see [Data Catalog Resource - Project] - (https://cloud.google.com/data-catalog/docs/concepts/resource-project) - for more information). - - Returns: - Callable[[~.DeleteTagTemplateFieldRequest], - 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_tag_template_field' not in self._stubs: - self._stubs['delete_tag_template_field'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTagTemplateField', - request_serializer=datacatalog.DeleteTagTemplateFieldRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag_template_field'] - - @property - def create_tag(self) -> Callable[ - [datacatalog.CreateTagRequest], - Awaitable[tags.Tag]]: - r"""Return a callable for the create tag method over gRPC. - - Creates a tag on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. Note: The - project identified by the ``parent`` parameter for the - `tag `__ - and the `tag - template `__ - used to create the tag must be from the same organization. - - Returns: - Callable[[~.CreateTagRequest], - Awaitable[~.Tag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['create_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/CreateTag', - request_serializer=datacatalog.CreateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['create_tag'] - - @property - def update_tag(self) -> Callable[ - [datacatalog.UpdateTagRequest], - Awaitable[tags.Tag]]: - r"""Return a callable for the update tag method over gRPC. - - Updates an existing tag. - - Returns: - Callable[[~.UpdateTagRequest], - Awaitable[~.Tag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag' not in self._stubs: - self._stubs['update_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/UpdateTag', - request_serializer=datacatalog.UpdateTagRequest.serialize, - response_deserializer=tags.Tag.deserialize, - ) - return self._stubs['update_tag'] - - @property - def delete_tag(self) -> Callable[ - [datacatalog.DeleteTagRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete tag method over gRPC. - - Deletes a tag. - - Returns: - Callable[[~.DeleteTagRequest], - 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_tag' not in self._stubs: - self._stubs['delete_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/DeleteTag', - request_serializer=datacatalog.DeleteTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_tag'] - - @property - def list_tags(self) -> Callable[ - [datacatalog.ListTagsRequest], - Awaitable[datacatalog.ListTagsResponse]]: - r"""Return a callable for the list tags method over gRPC. - - Lists the tags on an - [Entry][google.cloud.datacatalog.v1beta1.Entry]. - - Returns: - Callable[[~.ListTagsRequest], - Awaitable[~.ListTagsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tags' not in self._stubs: - self._stubs['list_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/ListTags', - request_serializer=datacatalog.ListTagsRequest.serialize, - response_deserializer=datacatalog.ListTagsResponse.deserialize, - ) - return self._stubs['list_tags'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy for a resource. Replaces any - existing policy. Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.setIamPolicy`` to set policies on - tag templates. - - ``datacatalog.entries.setIamPolicy`` to set policies on - entries. - - ``datacatalog.entryGroups.setIamPolicy`` to set policies on - entry groups. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. A ``NOT_FOUND`` - error is returned if the resource does not exist. An empty - policy is returned if the resource exists but does not have a - policy set on it. - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - Callers must have following Google IAM permission - - - ``datacatalog.tagTemplates.getIamPolicy`` to get policies on - tag templates. - - ``datacatalog.entries.getIamPolicy`` to get policies on - entries. - - ``datacatalog.entryGroups.getIamPolicy`` to get policies on - entry groups. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the caller's permissions on a resource. If the resource - does not exist, an empty set of permissions is returned (We - don't return a ``NOT_FOUND`` error). - - Supported resources are: - - - Tag templates. - - Entries. - - Entry groups. Note, this method cannot be used to manage - policies for BigQuery, Pub/Sub and any external Google Cloud - Platform resources synced to Data Catalog. - - A caller is not required to have Google IAM permission to make - this request. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.DataCatalog/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DataCatalogGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__init__.py deleted file mode 100644 index 3d4e08a0..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/__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 PolicyTagManagerClient -from .async_client import PolicyTagManagerAsyncClient - -__all__ = ( - 'PolicyTagManagerClient', - 'PolicyTagManagerAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py deleted file mode 100644 index e5af6b24..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/async_client.py +++ /dev/null @@ -1,1263 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport -from .client import PolicyTagManagerClient - - -class PolicyTagManagerAsyncClient: - """The policy tag manager API service allows clients to manage - their taxonomies and policy tags. - """ - - _client: PolicyTagManagerClient - - DEFAULT_ENDPOINT = PolicyTagManagerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PolicyTagManagerClient.DEFAULT_MTLS_ENDPOINT - - policy_tag_path = staticmethod(PolicyTagManagerClient.policy_tag_path) - parse_policy_tag_path = staticmethod(PolicyTagManagerClient.parse_policy_tag_path) - taxonomy_path = staticmethod(PolicyTagManagerClient.taxonomy_path) - parse_taxonomy_path = staticmethod(PolicyTagManagerClient.parse_taxonomy_path) - common_billing_account_path = staticmethod(PolicyTagManagerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PolicyTagManagerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PolicyTagManagerClient.common_folder_path) - parse_common_folder_path = staticmethod(PolicyTagManagerClient.parse_common_folder_path) - common_organization_path = staticmethod(PolicyTagManagerClient.common_organization_path) - parse_common_organization_path = staticmethod(PolicyTagManagerClient.parse_common_organization_path) - common_project_path = staticmethod(PolicyTagManagerClient.common_project_path) - parse_common_project_path = staticmethod(PolicyTagManagerClient.parse_common_project_path) - common_location_path = staticmethod(PolicyTagManagerClient.common_location_path) - parse_common_location_path = staticmethod(PolicyTagManagerClient.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: - PolicyTagManagerAsyncClient: The constructed client. - """ - return PolicyTagManagerClient.from_service_account_info.__func__(PolicyTagManagerAsyncClient, 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: - PolicyTagManagerAsyncClient: The constructed client. - """ - return PolicyTagManagerClient.from_service_account_file.__func__(PolicyTagManagerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PolicyTagManagerTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PolicyTagManagerClient).get_transport_class, type(PolicyTagManagerClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PolicyTagManagerTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager 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, ~.PolicyTagManagerTransport]): 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 = PolicyTagManagerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_taxonomy(self, - request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, - *, - parent: str = None, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Creates a taxonomy in the specified project. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTaxonomyRequest, dict]): - The request object. Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. - parent (:class:`str`): - Required. Resource name of the - project that the taxonomy will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - taxonomy (:class:`google.cloud.datacatalog_v1beta1.types.Taxonomy`): - The taxonomy to be created. - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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, taxonomy]) - if request is 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 = policytagmanager.CreateTaxonomyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if taxonomy is not None: - request.taxonomy = taxonomy - - # 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_taxonomy, - default_timeout=None, - client_info=DEFAULT_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 delete_taxonomy(self, - request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a taxonomy. This operation will also delete - all policy tags in this taxonomy along with their - associated policies. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTaxonomyRequest, dict]): - The request object. Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. - name (:class:`str`): - Required. Resource name of the - taxonomy to be deleted. All policy tags - in this taxonomy will also be deleted. - - 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 = policytagmanager.DeleteTaxonomyRequest(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_taxonomy, - default_timeout=None, - client_info=DEFAULT_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 update_taxonomy(self, - request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, - *, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Updates a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTaxonomyRequest, dict]): - The request object. Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. - taxonomy (:class:`google.cloud.datacatalog_v1beta1.types.Taxonomy`): - The taxonomy to update. Only description, display_name, - and activated policy types can be updated. - - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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([taxonomy]) - if request is 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 = policytagmanager.UpdateTaxonomyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if taxonomy is not None: - request.taxonomy = taxonomy - - # 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_taxonomy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("taxonomy.name", request.taxonomy.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_taxonomies(self, - request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTaxonomiesAsyncPager: - r"""Lists all taxonomies in a project in a particular - location that the caller has permission to view. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListTaxonomiesRequest, dict]): - The request object. Request message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - parent (:class:`str`): - Required. Resource name of the - project to list the taxonomies of. - - 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListTaxonomiesAsyncPager: - Response message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - - 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 = policytagmanager.ListTaxonomiesRequest(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_taxonomies, - default_timeout=None, - client_info=DEFAULT_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.ListTaxonomiesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_taxonomy(self, - request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Gets a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetTaxonomyRequest, dict]): - The request object. Request message for - [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. - name (:class:`str`): - Required. Resource name of the - requested taxonomy. - - 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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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 = policytagmanager.GetTaxonomyRequest(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_taxonomy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_policy_tag(self, - request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, - *, - parent: str = None, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Creates a policy tag in the specified taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreatePolicyTagRequest, dict]): - The request object. Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. - parent (:class:`str`): - Required. Resource name of the - taxonomy that the policy tag will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - policy_tag (:class:`google.cloud.datacatalog_v1beta1.types.PolicyTag`): - The policy tag to be created. - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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, policy_tag]) - if request is 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 = policytagmanager.CreatePolicyTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if policy_tag is not None: - request.policy_tag = policy_tag - - # 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_policy_tag, - default_timeout=None, - client_info=DEFAULT_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 delete_policy_tag(self, - request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a policy tag. Also deletes all of its - descendant policy tags. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeletePolicyTagRequest, dict]): - The request object. Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. - name (:class:`str`): - Required. Resource name of the policy - tag to be deleted. All of its descendant - policy tags will also be deleted. - - 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 = policytagmanager.DeletePolicyTagRequest(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_policy_tag, - default_timeout=None, - client_info=DEFAULT_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 update_policy_tag(self, - request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, - *, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Updates a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdatePolicyTagRequest, dict]): - The request object. Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. - policy_tag (:class:`google.cloud.datacatalog_v1beta1.types.PolicyTag`): - The policy tag to update. Only the description, - display_name, and parent_policy_tag fields can be - updated. - - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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([policy_tag]) - if request is 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 = policytagmanager.UpdatePolicyTagRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if policy_tag is not None: - request.policy_tag = policy_tag - - # 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_policy_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("policy_tag.name", request.policy_tag.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_policy_tags(self, - request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPolicyTagsAsyncPager: - r"""Lists all policy tags in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListPolicyTagsRequest, dict]): - The request object. Request message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - parent (:class:`str`): - Required. Resource name of the - taxonomy to list the policy tags of. - - 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListPolicyTagsAsyncPager: - Response message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - - 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 = policytagmanager.ListPolicyTagsRequest(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_policy_tags, - default_timeout=None, - client_info=DEFAULT_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.ListPolicyTagsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_policy_tag(self, - request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Gets a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetPolicyTagRequest, dict]): - The request object. Request message for - [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. - name (:class:`str`): - Required. Resource name of the - requested policy tag. - - 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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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 = policytagmanager.GetPolicyTagRequest(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_policy_tag, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM policy for a taxonomy or a policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM policy for a taxonomy or a policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified taxonomy or policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py deleted file mode 100644 index 7ce73c28..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py +++ /dev/null @@ -1,1466 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .transports.base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PolicyTagManagerGrpcTransport -from .transports.grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport - - -class PolicyTagManagerClientMeta(type): - """Metaclass for the PolicyTagManager 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[PolicyTagManagerTransport]] - _transport_registry["grpc"] = PolicyTagManagerGrpcTransport - _transport_registry["grpc_asyncio"] = PolicyTagManagerGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PolicyTagManagerTransport]: - """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 PolicyTagManagerClient(metaclass=PolicyTagManagerClientMeta): - """The policy tag manager API service allows clients to manage - their taxonomies and policy tags. - """ - - @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 = "datacatalog.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: - PolicyTagManagerClient: 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: - PolicyTagManagerClient: 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) -> PolicyTagManagerTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def policy_tag_path(project: str,location: str,taxonomy: str,policy_tag: str,) -> str: - """Returns a fully-qualified policy_tag string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) - - @staticmethod - def parse_policy_tag_path(path: str) -> Dict[str,str]: - """Parses a policy_tag path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?P.+?)/policyTags/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: - """Returns a fully-qualified taxonomy string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - - @staticmethod - def parse_taxonomy_path(path: str) -> Dict[str,str]: - """Parses a taxonomy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager 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, PolicyTagManagerTransport]): 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, PolicyTagManagerTransport): - # transport is a PolicyTagManagerTransport 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=True, - ) - - def create_taxonomy(self, - request: Union[policytagmanager.CreateTaxonomyRequest, dict] = None, - *, - parent: str = None, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Creates a taxonomy in the specified project. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreateTaxonomyRequest, dict]): - The request object. Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. - parent (str): - Required. Resource name of the - project that the taxonomy will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): - The taxonomy to be created. - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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, taxonomy]) - if request is 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 policytagmanager.CreateTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.CreateTaxonomyRequest): - request = policytagmanager.CreateTaxonomyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if taxonomy is not None: - request.taxonomy = taxonomy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_taxonomy] - - # 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 delete_taxonomy(self, - request: Union[policytagmanager.DeleteTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a taxonomy. This operation will also delete - all policy tags in this taxonomy along with their - associated policies. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeleteTaxonomyRequest, dict]): - The request object. Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. - name (str): - Required. Resource name of the - taxonomy to be deleted. All policy tags - in this taxonomy will also be deleted. - - 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 policytagmanager.DeleteTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.DeleteTaxonomyRequest): - request = policytagmanager.DeleteTaxonomyRequest(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_taxonomy] - - # Certain fields should be 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 update_taxonomy(self, - request: Union[policytagmanager.UpdateTaxonomyRequest, dict] = None, - *, - taxonomy: policytagmanager.Taxonomy = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Updates a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdateTaxonomyRequest, dict]): - The request object. Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. - taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): - The taxonomy to update. Only description, display_name, - and activated policy types can be updated. - - This corresponds to the ``taxonomy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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([taxonomy]) - if request is 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 policytagmanager.UpdateTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.UpdateTaxonomyRequest): - request = policytagmanager.UpdateTaxonomyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if taxonomy is not None: - request.taxonomy = taxonomy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_taxonomy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("taxonomy.name", request.taxonomy.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_taxonomies(self, - request: Union[policytagmanager.ListTaxonomiesRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTaxonomiesPager: - r"""Lists all taxonomies in a project in a particular - location that the caller has permission to view. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListTaxonomiesRequest, dict]): - The request object. Request message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - parent (str): - Required. Resource name of the - project to list the taxonomies of. - - 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListTaxonomiesPager: - Response message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - - 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 policytagmanager.ListTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.ListTaxonomiesRequest): - request = policytagmanager.ListTaxonomiesRequest(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_taxonomies] - - # 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.ListTaxonomiesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_taxonomy(self, - request: Union[policytagmanager.GetTaxonomyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.Taxonomy: - r"""Gets a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetTaxonomyRequest, dict]): - The request object. Request message for - [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. - name (str): - Required. Resource name of the - requested taxonomy. - - 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.datacatalog_v1beta1.types.Taxonomy: - A taxonomy is a collection of policy tags that classify data along a common - axis. For instance a data *sensitivity* taxonomy - could contain policy tags denoting PII such as age, - zipcode, and SSN. A data *origin* taxonomy could - contain policy tags to distinguish user data, - employee data, partner data, public data. - - """ - # 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 policytagmanager.GetTaxonomyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.GetTaxonomyRequest): - request = policytagmanager.GetTaxonomyRequest(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_taxonomy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_policy_tag(self, - request: Union[policytagmanager.CreatePolicyTagRequest, dict] = None, - *, - parent: str = None, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Creates a policy tag in the specified taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.CreatePolicyTagRequest, dict]): - The request object. Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. - parent (str): - Required. Resource name of the - taxonomy that the policy tag will belong - to. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): - The policy tag to be created. - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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, policy_tag]) - if request is 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 policytagmanager.CreatePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.CreatePolicyTagRequest): - request = policytagmanager.CreatePolicyTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if policy_tag is not None: - request.policy_tag = policy_tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_policy_tag] - - # 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 delete_policy_tag(self, - request: Union[policytagmanager.DeletePolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a policy tag. Also deletes all of its - descendant policy tags. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.DeletePolicyTagRequest, dict]): - The request object. Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. - name (str): - Required. Resource name of the policy - tag to be deleted. All of its descendant - policy tags will also be deleted. - - 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 policytagmanager.DeletePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.DeletePolicyTagRequest): - request = policytagmanager.DeletePolicyTagRequest(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_policy_tag] - - # Certain fields should be 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 update_policy_tag(self, - request: Union[policytagmanager.UpdatePolicyTagRequest, dict] = None, - *, - policy_tag: policytagmanager.PolicyTag = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Updates a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.UpdatePolicyTagRequest, dict]): - The request object. Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. - policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): - The policy tag to update. Only the description, - display_name, and parent_policy_tag fields can be - updated. - - This corresponds to the ``policy_tag`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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([policy_tag]) - if request is 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 policytagmanager.UpdatePolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.UpdatePolicyTagRequest): - request = policytagmanager.UpdatePolicyTagRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if policy_tag is not None: - request.policy_tag = policy_tag - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_policy_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("policy_tag.name", request.policy_tag.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_policy_tags(self, - request: Union[policytagmanager.ListPolicyTagsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPolicyTagsPager: - r"""Lists all policy tags in a taxonomy. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ListPolicyTagsRequest, dict]): - The request object. Request message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - parent (str): - Required. Resource name of the - taxonomy to list the policy tags of. - - 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.datacatalog_v1beta1.services.policy_tag_manager.pagers.ListPolicyTagsPager: - Response message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - - 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 policytagmanager.ListPolicyTagsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.ListPolicyTagsRequest): - request = policytagmanager.ListPolicyTagsRequest(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_policy_tags] - - # 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.ListPolicyTagsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_policy_tag(self, - request: Union[policytagmanager.GetPolicyTagRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanager.PolicyTag: - r"""Gets a policy tag. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.GetPolicyTagRequest, dict]): - The request object. Request message for - [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. - name (str): - Required. Resource name of the - requested policy tag. - - 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.datacatalog_v1beta1.types.PolicyTag: - Denotes one policy tag in a taxonomy - (e.g. ssn). Policy Tags can be defined - in a hierarchy. For example, consider - the following hierarchy: Geolocation - -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three - child policy tags: "LatLong", "City", - and "ZipCode". - - """ - # 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 policytagmanager.GetPolicyTagRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanager.GetPolicyTagRequest): - request = policytagmanager.GetPolicyTagRequest(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_policy_tag] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Union[iam_policy_pb2.GetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM policy for a taxonomy or a policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Union[iam_policy_pb2.SetIamPolicyRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM policy for a taxonomy or a policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. It is used to - specify access control policies for Cloud Platform - resources. - - A Policy is a collection of bindings. A binding binds - one or more members to a single role. Members can be - user accounts, service accounts, Google groups, and - domains (such as G Suite). A role is a named list of - permissions (defined by IAM or configured by users). - A binding can optionally specify a condition, which - is a logic expression that further constrains the - role binding based on attributes about the request - and/or target resource. - - **JSON Example** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ] - - } - - **YAML Example** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the - [IAM developer's - guide](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Union[iam_policy_pb2.TestIamPermissionsRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified taxonomy or policy tag. - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py deleted file mode 100644 index 6ccf41e2..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/pagers.py +++ /dev/null @@ -1,262 +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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.datacatalog_v1beta1.types import policytagmanager - - -class ListTaxonomiesPager: - """A pager for iterating through ``list_taxonomies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``taxonomies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTaxonomies`` requests and continue to iterate - through the ``taxonomies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` - 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[..., policytagmanager.ListTaxonomiesResponse], - request: policytagmanager.ListTaxonomiesRequest, - response: policytagmanager.ListTaxonomiesResponse, - *, - 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.datacatalog_v1beta1.types.ListTaxonomiesRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse): - 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 = policytagmanager.ListTaxonomiesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[policytagmanager.ListTaxonomiesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[policytagmanager.Taxonomy]: - for page in self.pages: - yield from page.taxonomies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTaxonomiesAsyncPager: - """A pager for iterating through ``list_taxonomies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``taxonomies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTaxonomies`` requests and continue to iterate - through the ``taxonomies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse` - 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[policytagmanager.ListTaxonomiesResponse]], - request: policytagmanager.ListTaxonomiesRequest, - response: policytagmanager.ListTaxonomiesResponse, - *, - 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.datacatalog_v1beta1.types.ListTaxonomiesRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListTaxonomiesResponse): - 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 = policytagmanager.ListTaxonomiesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[policytagmanager.ListTaxonomiesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[policytagmanager.Taxonomy]: - async def async_generator(): - async for page in self.pages: - for response in page.taxonomies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPolicyTagsPager: - """A pager for iterating through ``list_policy_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``policy_tags`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPolicyTags`` requests and continue to iterate - through the ``policy_tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` - 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[..., policytagmanager.ListPolicyTagsResponse], - request: policytagmanager.ListPolicyTagsRequest, - response: policytagmanager.ListPolicyTagsResponse, - *, - 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.datacatalog_v1beta1.types.ListPolicyTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse): - 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 = policytagmanager.ListPolicyTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[policytagmanager.ListPolicyTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[policytagmanager.PolicyTag]: - for page in self.pages: - yield from page.policy_tags - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPolicyTagsAsyncPager: - """A pager for iterating through ``list_policy_tags`` requests. - - This class thinly wraps an initial - :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``policy_tags`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPolicyTags`` requests and continue to iterate - through the ``policy_tags`` field on the - corresponding responses. - - All the usual :class:`google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse` - 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[policytagmanager.ListPolicyTagsResponse]], - request: policytagmanager.ListPolicyTagsRequest, - response: policytagmanager.ListPolicyTagsResponse, - *, - 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.datacatalog_v1beta1.types.ListPolicyTagsRequest): - The initial request object. - response (google.cloud.datacatalog_v1beta1.types.ListPolicyTagsResponse): - 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 = policytagmanager.ListPolicyTagsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[policytagmanager.ListPolicyTagsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[policytagmanager.PolicyTag]: - async def async_generator(): - async for page in self.pages: - for response in page.policy_tags: - 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/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/__init__.py deleted file mode 100644 index d76a9c05..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/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 PolicyTagManagerTransport -from .grpc import PolicyTagManagerGrpcTransport -from .grpc_asyncio import PolicyTagManagerGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerTransport]] -_transport_registry['grpc'] = PolicyTagManagerGrpcTransport -_transport_registry['grpc_asyncio'] = PolicyTagManagerGrpcAsyncIOTransport - -__all__ = ( - 'PolicyTagManagerTransport', - 'PolicyTagManagerGrpcTransport', - 'PolicyTagManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py deleted file mode 100644 index 0e61f950..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/base.py +++ /dev/null @@ -1,317 +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 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.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -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-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PolicyTagManagerTransport(abc.ABC): - """Abstract transport class for PolicyTagManager.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_taxonomy: gapic_v1.method.wrap_method( - self.create_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.delete_taxonomy: gapic_v1.method.wrap_method( - self.delete_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.update_taxonomy: gapic_v1.method.wrap_method( - self.update_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.list_taxonomies: gapic_v1.method.wrap_method( - self.list_taxonomies, - default_timeout=None, - client_info=client_info, - ), - self.get_taxonomy: gapic_v1.method.wrap_method( - self.get_taxonomy, - default_timeout=None, - client_info=client_info, - ), - self.create_policy_tag: gapic_v1.method.wrap_method( - self.create_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.delete_policy_tag: gapic_v1.method.wrap_method( - self.delete_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.update_policy_tag: gapic_v1.method.wrap_method( - self.update_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.list_policy_tags: gapic_v1.method.wrap_method( - self.list_policy_tags, - default_timeout=None, - client_info=client_info, - ), - self.get_policy_tag: gapic_v1.method.wrap_method( - self.get_policy_tag, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - Union[ - policytagmanager.ListTaxonomiesResponse, - Awaitable[policytagmanager.ListTaxonomiesResponse] - ]]: - raise NotImplementedError() - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - Union[ - policytagmanager.Taxonomy, - Awaitable[policytagmanager.Taxonomy] - ]]: - raise NotImplementedError() - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - Union[ - policytagmanager.ListPolicyTagsResponse, - Awaitable[policytagmanager.ListPolicyTagsResponse] - ]]: - raise NotImplementedError() - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - Union[ - policytagmanager.PolicyTag, - Awaitable[policytagmanager.PolicyTag] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PolicyTagManagerTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py deleted file mode 100644 index 63c211cb..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc.py +++ /dev/null @@ -1,575 +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.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO - - -class PolicyTagManagerGrpcTransport(PolicyTagManagerTransport): - """gRPC backend transport for PolicyTagManager. - - The policy tag manager API service allows clients to manage - their taxonomies and policy tags. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the create taxonomy method over gRPC. - - Creates a taxonomy in the specified project. - - Returns: - Callable[[~.CreateTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreateTaxonomy', - request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['create_taxonomy'] - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete taxonomy method over gRPC. - - Deletes a taxonomy. This operation will also delete - all policy tags in this taxonomy along with their - associated policies. - - Returns: - Callable[[~.DeleteTaxonomyRequest], - ~.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_taxonomy' not in self._stubs: - self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeleteTaxonomy', - request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_taxonomy'] - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the update taxonomy method over gRPC. - - Updates a taxonomy. - - Returns: - Callable[[~.UpdateTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdateTaxonomy', - request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['update_taxonomy'] - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - policytagmanager.ListTaxonomiesResponse]: - r"""Return a callable for the list taxonomies method over gRPC. - - Lists all taxonomies in a project in a particular - location that the caller has permission to view. - - Returns: - Callable[[~.ListTaxonomiesRequest], - ~.ListTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: - self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListTaxonomies', - request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, - response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, - ) - return self._stubs['list_taxonomies'] - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - policytagmanager.Taxonomy]: - r"""Return a callable for the get taxonomy method over gRPC. - - Gets a taxonomy. - - Returns: - Callable[[~.GetTaxonomyRequest], - ~.Taxonomy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetTaxonomy', - request_serializer=policytagmanager.GetTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['get_taxonomy'] - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the create policy tag method over gRPC. - - Creates a policy tag in the specified taxonomy. - - Returns: - Callable[[~.CreatePolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreatePolicyTag', - request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['create_policy_tag'] - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete policy tag method over gRPC. - - Deletes a policy tag. Also deletes all of its - descendant policy tags. - - Returns: - Callable[[~.DeletePolicyTagRequest], - ~.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_policy_tag' not in self._stubs: - self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeletePolicyTag', - request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_policy_tag'] - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the update policy tag method over gRPC. - - Updates a policy tag. - - Returns: - Callable[[~.UpdatePolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdatePolicyTag', - request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['update_policy_tag'] - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - policytagmanager.ListPolicyTagsResponse]: - r"""Return a callable for the list policy tags method over gRPC. - - Lists all policy tags in a taxonomy. - - Returns: - Callable[[~.ListPolicyTagsRequest], - ~.ListPolicyTagsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: - self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListPolicyTags', - request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, - response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, - ) - return self._stubs['list_policy_tags'] - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - policytagmanager.PolicyTag]: - r"""Return a callable for the get policy tag method over gRPC. - - Gets a policy tag. - - Returns: - Callable[[~.GetPolicyTagRequest], - ~.PolicyTag]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetPolicyTag', - request_serializer=policytagmanager.GetPolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['get_policy_tag'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM policy for a taxonomy or a policy tag. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM policy for a taxonomy or a policy tag. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified taxonomy or policy tag. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'PolicyTagManagerGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py deleted file mode 100644 index b7c1b991..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/transports/grpc_asyncio.py +++ /dev/null @@ -1,579 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import PolicyTagManagerTransport, DEFAULT_CLIENT_INFO -from .grpc import PolicyTagManagerGrpcTransport - - -class PolicyTagManagerGrpcAsyncIOTransport(PolicyTagManagerTransport): - """gRPC AsyncIO backend transport for PolicyTagManager. - - The policy tag manager API service allows clients to manage - their taxonomies and policy tags. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 create_taxonomy(self) -> Callable[ - [policytagmanager.CreateTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the create taxonomy method over gRPC. - - Creates a taxonomy in the specified project. - - Returns: - Callable[[~.CreateTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['create_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreateTaxonomy', - request_serializer=policytagmanager.CreateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['create_taxonomy'] - - @property - def delete_taxonomy(self) -> Callable[ - [policytagmanager.DeleteTaxonomyRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete taxonomy method over gRPC. - - Deletes a taxonomy. This operation will also delete - all policy tags in this taxonomy along with their - associated policies. - - Returns: - Callable[[~.DeleteTaxonomyRequest], - 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_taxonomy' not in self._stubs: - self._stubs['delete_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeleteTaxonomy', - request_serializer=policytagmanager.DeleteTaxonomyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_taxonomy'] - - @property - def update_taxonomy(self) -> Callable[ - [policytagmanager.UpdateTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the update taxonomy method over gRPC. - - Updates a taxonomy. - - Returns: - Callable[[~.UpdateTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['update_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdateTaxonomy', - request_serializer=policytagmanager.UpdateTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['update_taxonomy'] - - @property - def list_taxonomies(self) -> Callable[ - [policytagmanager.ListTaxonomiesRequest], - Awaitable[policytagmanager.ListTaxonomiesResponse]]: - r"""Return a callable for the list taxonomies method over gRPC. - - Lists all taxonomies in a project in a particular - location that the caller has permission to view. - - Returns: - Callable[[~.ListTaxonomiesRequest], - Awaitable[~.ListTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomies' not in self._stubs: - self._stubs['list_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListTaxonomies', - request_serializer=policytagmanager.ListTaxonomiesRequest.serialize, - response_deserializer=policytagmanager.ListTaxonomiesResponse.deserialize, - ) - return self._stubs['list_taxonomies'] - - @property - def get_taxonomy(self) -> Callable[ - [policytagmanager.GetTaxonomyRequest], - Awaitable[policytagmanager.Taxonomy]]: - r"""Return a callable for the get taxonomy method over gRPC. - - Gets a taxonomy. - - Returns: - Callable[[~.GetTaxonomyRequest], - Awaitable[~.Taxonomy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_taxonomy' not in self._stubs: - self._stubs['get_taxonomy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetTaxonomy', - request_serializer=policytagmanager.GetTaxonomyRequest.serialize, - response_deserializer=policytagmanager.Taxonomy.deserialize, - ) - return self._stubs['get_taxonomy'] - - @property - def create_policy_tag(self) -> Callable[ - [policytagmanager.CreatePolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the create policy tag method over gRPC. - - Creates a policy tag in the specified taxonomy. - - Returns: - Callable[[~.CreatePolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['create_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/CreatePolicyTag', - request_serializer=policytagmanager.CreatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['create_policy_tag'] - - @property - def delete_policy_tag(self) -> Callable[ - [policytagmanager.DeletePolicyTagRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete policy tag method over gRPC. - - Deletes a policy tag. Also deletes all of its - descendant policy tags. - - Returns: - Callable[[~.DeletePolicyTagRequest], - 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_policy_tag' not in self._stubs: - self._stubs['delete_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/DeletePolicyTag', - request_serializer=policytagmanager.DeletePolicyTagRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_policy_tag'] - - @property - def update_policy_tag(self) -> Callable[ - [policytagmanager.UpdatePolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the update policy tag method over gRPC. - - Updates a policy tag. - - Returns: - Callable[[~.UpdatePolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['update_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/UpdatePolicyTag', - request_serializer=policytagmanager.UpdatePolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['update_policy_tag'] - - @property - def list_policy_tags(self) -> Callable[ - [policytagmanager.ListPolicyTagsRequest], - Awaitable[policytagmanager.ListPolicyTagsResponse]]: - r"""Return a callable for the list policy tags method over gRPC. - - Lists all policy tags in a taxonomy. - - Returns: - Callable[[~.ListPolicyTagsRequest], - Awaitable[~.ListPolicyTagsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tags' not in self._stubs: - self._stubs['list_policy_tags'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/ListPolicyTags', - request_serializer=policytagmanager.ListPolicyTagsRequest.serialize, - response_deserializer=policytagmanager.ListPolicyTagsResponse.deserialize, - ) - return self._stubs['list_policy_tags'] - - @property - def get_policy_tag(self) -> Callable[ - [policytagmanager.GetPolicyTagRequest], - Awaitable[policytagmanager.PolicyTag]]: - r"""Return a callable for the get policy tag method over gRPC. - - Gets a policy tag. - - Returns: - Callable[[~.GetPolicyTagRequest], - Awaitable[~.PolicyTag]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_policy_tag' not in self._stubs: - self._stubs['get_policy_tag'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetPolicyTag', - request_serializer=policytagmanager.GetPolicyTagRequest.serialize, - response_deserializer=policytagmanager.PolicyTag.deserialize, - ) - return self._stubs['get_policy_tag'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the IAM policy for a taxonomy or a policy tag. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the IAM policy for a taxonomy or a policy tag. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified taxonomy or policy tag. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PolicyTagManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__init__.py deleted file mode 100644 index 5e73ed2a..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/__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 PolicyTagManagerSerializationClient -from .async_client import PolicyTagManagerSerializationAsyncClient - -__all__ = ( - 'PolicyTagManagerSerializationClient', - 'PolicyTagManagerSerializationAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py deleted file mode 100644 index 8a7e1767..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/async_client.py +++ /dev/null @@ -1,288 +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 - -from google.api_core.client_options import 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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization -from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport -from .client import PolicyTagManagerSerializationClient - - -class PolicyTagManagerSerializationAsyncClient: - """Policy tag manager serialization API service allows clients - to manipulate their taxonomies and policy tags data with - serialized format. - """ - - _client: PolicyTagManagerSerializationClient - - DEFAULT_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PolicyTagManagerSerializationClient.DEFAULT_MTLS_ENDPOINT - - taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.taxonomy_path) - parse_taxonomy_path = staticmethod(PolicyTagManagerSerializationClient.parse_taxonomy_path) - common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PolicyTagManagerSerializationClient.common_folder_path) - parse_common_folder_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_folder_path) - common_organization_path = staticmethod(PolicyTagManagerSerializationClient.common_organization_path) - parse_common_organization_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_organization_path) - common_project_path = staticmethod(PolicyTagManagerSerializationClient.common_project_path) - parse_common_project_path = staticmethod(PolicyTagManagerSerializationClient.parse_common_project_path) - common_location_path = staticmethod(PolicyTagManagerSerializationClient.common_location_path) - parse_common_location_path = staticmethod(PolicyTagManagerSerializationClient.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: - PolicyTagManagerSerializationAsyncClient: The constructed client. - """ - return PolicyTagManagerSerializationClient.from_service_account_info.__func__(PolicyTagManagerSerializationAsyncClient, 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: - PolicyTagManagerSerializationAsyncClient: The constructed client. - """ - return PolicyTagManagerSerializationClient.from_service_account_file.__func__(PolicyTagManagerSerializationAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PolicyTagManagerSerializationTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerSerializationTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PolicyTagManagerSerializationClient).get_transport_class, type(PolicyTagManagerSerializationClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PolicyTagManagerSerializationTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager serialization 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, ~.PolicyTagManagerSerializationTransport]): 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 = PolicyTagManagerSerializationClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def import_taxonomies(self, - request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ImportTaxonomiesResponse: - r"""Imports all taxonomies and their policy tags to a - project as new taxonomies. - - This method provides a bulk taxonomy / policy tag - creation using nested proto structure. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ImportTaxonomiesRequest, dict]): - The request object. Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.ImportTaxonomiesResponse: - Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - request = policytagmanagerserialization.ImportTaxonomiesRequest(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.import_taxonomies, - default_timeout=None, - client_info=DEFAULT_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 export_taxonomies(self, - request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ExportTaxonomiesResponse: - r"""Exports all taxonomies and their policy tags in a - project. - This method generates SerializedTaxonomy protos with - nested policy tags that can be used as an input for - future ImportTaxonomies calls. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ExportTaxonomiesRequest, dict]): - The request object. Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.ExportTaxonomiesResponse: - Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - request = policytagmanagerserialization.ExportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_taxonomies, - default_timeout=None, - client_info=DEFAULT_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 __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerSerializationAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py deleted file mode 100644 index 9be6bd9d..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py +++ /dev/null @@ -1,487 +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 Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -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 - -OptionalRetry = Union[retries.Retry, object] - -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization -from .transports.base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PolicyTagManagerSerializationGrpcTransport -from .transports.grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport - - -class PolicyTagManagerSerializationClientMeta(type): - """Metaclass for the PolicyTagManagerSerialization 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[PolicyTagManagerSerializationTransport]] - _transport_registry["grpc"] = PolicyTagManagerSerializationGrpcTransport - _transport_registry["grpc_asyncio"] = PolicyTagManagerSerializationGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PolicyTagManagerSerializationTransport]: - """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 PolicyTagManagerSerializationClient(metaclass=PolicyTagManagerSerializationClientMeta): - """Policy tag manager serialization API service allows clients - to manipulate their taxonomies and policy tags data with - serialized format. - """ - - @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 = "datacatalog.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: - PolicyTagManagerSerializationClient: 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: - PolicyTagManagerSerializationClient: 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) -> PolicyTagManagerSerializationTransport: - """Returns the transport used by the client instance. - - Returns: - PolicyTagManagerSerializationTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def taxonomy_path(project: str,location: str,taxonomy: str,) -> str: - """Returns a fully-qualified taxonomy string.""" - return "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - - @staticmethod - def parse_taxonomy_path(path: str) -> Dict[str,str]: - """Parses a taxonomy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/taxonomies/(?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, PolicyTagManagerSerializationTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the policy tag manager serialization 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, PolicyTagManagerSerializationTransport]): 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, PolicyTagManagerSerializationTransport): - # transport is a PolicyTagManagerSerializationTransport 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=True, - ) - - def import_taxonomies(self, - request: Union[policytagmanagerserialization.ImportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ImportTaxonomiesResponse: - r"""Imports all taxonomies and their policy tags to a - project as new taxonomies. - - This method provides a bulk taxonomy / policy tag - creation using nested proto structure. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ImportTaxonomiesRequest, dict]): - The request object. Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.ImportTaxonomiesResponse: - Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a policytagmanagerserialization.ImportTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanagerserialization.ImportTaxonomiesRequest): - request = policytagmanagerserialization.ImportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_taxonomies] - - # 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 export_taxonomies(self, - request: Union[policytagmanagerserialization.ExportTaxonomiesRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policytagmanagerserialization.ExportTaxonomiesResponse: - r"""Exports all taxonomies and their policy tags in a - project. - This method generates SerializedTaxonomy protos with - nested policy tags that can be used as an input for - future ImportTaxonomies calls. - - Args: - request (Union[google.cloud.datacatalog_v1beta1.types.ExportTaxonomiesRequest, dict]): - The request object. Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.datacatalog_v1beta1.types.ExportTaxonomiesResponse: - Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a policytagmanagerserialization.ExportTaxonomiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, policytagmanagerserialization.ExportTaxonomiesRequest): - request = policytagmanagerserialization.ExportTaxonomiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_taxonomies] - - # 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 __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-datacatalog", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PolicyTagManagerSerializationClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/__init__.py deleted file mode 100644 index 2864dab0..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/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 PolicyTagManagerSerializationTransport -from .grpc import PolicyTagManagerSerializationGrpcTransport -from .grpc_asyncio import PolicyTagManagerSerializationGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PolicyTagManagerSerializationTransport]] -_transport_registry['grpc'] = PolicyTagManagerSerializationGrpcTransport -_transport_registry['grpc_asyncio'] = PolicyTagManagerSerializationGrpcAsyncIOTransport - -__all__ = ( - 'PolicyTagManagerSerializationTransport', - 'PolicyTagManagerSerializationGrpcTransport', - 'PolicyTagManagerSerializationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py deleted file mode 100644 index 42853f2b..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/base.py +++ /dev/null @@ -1,160 +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 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.datacatalog_v1beta1.types import policytagmanagerserialization - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-datacatalog', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class PolicyTagManagerSerializationTransport(abc.ABC): - """Abstract transport class for PolicyTagManagerSerialization.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'datacatalog.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.import_taxonomies: gapic_v1.method.wrap_method( - self.import_taxonomies, - default_timeout=None, - client_info=client_info, - ), - self.export_taxonomies: gapic_v1.method.wrap_method( - self.export_taxonomies, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - Union[ - policytagmanagerserialization.ImportTaxonomiesResponse, - Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse] - ]]: - raise NotImplementedError() - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - Union[ - policytagmanagerserialization.ExportTaxonomiesResponse, - Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PolicyTagManagerSerializationTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py deleted file mode 100644 index 0fd74180..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc.py +++ /dev/null @@ -1,290 +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.datacatalog_v1beta1.types import policytagmanagerserialization -from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO - - -class PolicyTagManagerSerializationGrpcTransport(PolicyTagManagerSerializationTransport): - """gRPC backend transport for PolicyTagManagerSerialization. - - Policy tag manager serialization API service allows clients - to manipulate their taxonomies and policy tags data with - serialized format. - - 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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 = 'datacatalog.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 import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - policytagmanagerserialization.ImportTaxonomiesResponse]: - r"""Return a callable for the import taxonomies method over gRPC. - - Imports all taxonomies and their policy tags to a - project as new taxonomies. - - This method provides a bulk taxonomy / policy tag - creation using nested proto structure. - - Returns: - Callable[[~.ImportTaxonomiesRequest], - ~.ImportTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_taxonomies' not in self._stubs: - self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ImportTaxonomies', - request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, - ) - return self._stubs['import_taxonomies'] - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - policytagmanagerserialization.ExportTaxonomiesResponse]: - r"""Return a callable for the export taxonomies method over gRPC. - - Exports all taxonomies and their policy tags in a - project. - This method generates SerializedTaxonomy protos with - nested policy tags that can be used as an input for - future ImportTaxonomies calls. - - Returns: - Callable[[~.ExportTaxonomiesRequest], - ~.ExportTaxonomiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_taxonomies' not in self._stubs: - self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ExportTaxonomies', - request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, - ) - return self._stubs['export_taxonomies'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'PolicyTagManagerSerializationGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py deleted file mode 100644 index d983db3f..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/transports/grpc_asyncio.py +++ /dev/null @@ -1,294 +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 grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization -from .base import PolicyTagManagerSerializationTransport, DEFAULT_CLIENT_INFO -from .grpc import PolicyTagManagerSerializationGrpcTransport - - -class PolicyTagManagerSerializationGrpcAsyncIOTransport(PolicyTagManagerSerializationTransport): - """gRPC AsyncIO backend transport for PolicyTagManagerSerialization. - - Policy tag manager serialization API service allows clients - to manipulate their taxonomies and policy tags data with - serialized format. - - 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 = 'datacatalog.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 = 'datacatalog.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 application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - 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 import_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ImportTaxonomiesRequest], - Awaitable[policytagmanagerserialization.ImportTaxonomiesResponse]]: - r"""Return a callable for the import taxonomies method over gRPC. - - Imports all taxonomies and their policy tags to a - project as new taxonomies. - - This method provides a bulk taxonomy / policy tag - creation using nested proto structure. - - Returns: - Callable[[~.ImportTaxonomiesRequest], - Awaitable[~.ImportTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_taxonomies' not in self._stubs: - self._stubs['import_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ImportTaxonomies', - request_serializer=policytagmanagerserialization.ImportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ImportTaxonomiesResponse.deserialize, - ) - return self._stubs['import_taxonomies'] - - @property - def export_taxonomies(self) -> Callable[ - [policytagmanagerserialization.ExportTaxonomiesRequest], - Awaitable[policytagmanagerserialization.ExportTaxonomiesResponse]]: - r"""Return a callable for the export taxonomies method over gRPC. - - Exports all taxonomies and their policy tags in a - project. - This method generates SerializedTaxonomy protos with - nested policy tags that can be used as an input for - future ImportTaxonomies calls. - - Returns: - Callable[[~.ExportTaxonomiesRequest], - Awaitable[~.ExportTaxonomiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_taxonomies' not in self._stubs: - self._stubs['export_taxonomies'] = self.grpc_channel.unary_unary( - '/google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization/ExportTaxonomies', - request_serializer=policytagmanagerserialization.ExportTaxonomiesRequest.serialize, - response_deserializer=policytagmanagerserialization.ExportTaxonomiesResponse.deserialize, - ) - return self._stubs['export_taxonomies'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'PolicyTagManagerSerializationGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py deleted file mode 100644 index 1f5276b8..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/__init__.py +++ /dev/null @@ -1,175 +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 .datacatalog import ( - CreateEntryGroupRequest, - CreateEntryRequest, - CreateTagRequest, - CreateTagTemplateFieldRequest, - CreateTagTemplateRequest, - DeleteEntryGroupRequest, - DeleteEntryRequest, - DeleteTagRequest, - DeleteTagTemplateFieldRequest, - DeleteTagTemplateRequest, - Entry, - EntryGroup, - GetEntryGroupRequest, - GetEntryRequest, - GetTagTemplateRequest, - ListEntriesRequest, - ListEntriesResponse, - ListEntryGroupsRequest, - ListEntryGroupsResponse, - ListTagsRequest, - ListTagsResponse, - LookupEntryRequest, - RenameTagTemplateFieldRequest, - SearchCatalogRequest, - SearchCatalogResponse, - UpdateEntryGroupRequest, - UpdateEntryRequest, - UpdateTagRequest, - UpdateTagTemplateFieldRequest, - UpdateTagTemplateRequest, - EntryType, -) -from .gcs_fileset_spec import ( - GcsFilesetSpec, - GcsFileSpec, -) -from .policytagmanager import ( - CreatePolicyTagRequest, - CreateTaxonomyRequest, - DeletePolicyTagRequest, - DeleteTaxonomyRequest, - GetPolicyTagRequest, - GetTaxonomyRequest, - ListPolicyTagsRequest, - ListPolicyTagsResponse, - ListTaxonomiesRequest, - ListTaxonomiesResponse, - PolicyTag, - Taxonomy, - UpdatePolicyTagRequest, - UpdateTaxonomyRequest, -) -from .policytagmanagerserialization import ( - ExportTaxonomiesRequest, - ExportTaxonomiesResponse, - ImportTaxonomiesRequest, - ImportTaxonomiesResponse, - InlineSource, - SerializedPolicyTag, - SerializedTaxonomy, -) -from .schema import ( - ColumnSchema, - Schema, -) -from .search import ( - SearchCatalogResult, - SearchResultType, -) -from .table_spec import ( - BigQueryDateShardedSpec, - BigQueryTableSpec, - TableSpec, - ViewSpec, - TableSourceType, -) -from .tags import ( - FieldType, - Tag, - TagField, - TagTemplate, - TagTemplateField, -) -from .timestamps import ( - SystemTimestamps, -) - -__all__ = ( - 'IntegratedSystem', - 'CreateEntryGroupRequest', - 'CreateEntryRequest', - 'CreateTagRequest', - 'CreateTagTemplateFieldRequest', - 'CreateTagTemplateRequest', - 'DeleteEntryGroupRequest', - 'DeleteEntryRequest', - 'DeleteTagRequest', - 'DeleteTagTemplateFieldRequest', - 'DeleteTagTemplateRequest', - 'Entry', - 'EntryGroup', - 'GetEntryGroupRequest', - 'GetEntryRequest', - 'GetTagTemplateRequest', - 'ListEntriesRequest', - 'ListEntriesResponse', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'ListTagsRequest', - 'ListTagsResponse', - 'LookupEntryRequest', - 'RenameTagTemplateFieldRequest', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'UpdateEntryGroupRequest', - 'UpdateEntryRequest', - 'UpdateTagRequest', - 'UpdateTagTemplateFieldRequest', - 'UpdateTagTemplateRequest', - 'EntryType', - 'GcsFilesetSpec', - 'GcsFileSpec', - 'CreatePolicyTagRequest', - 'CreateTaxonomyRequest', - 'DeletePolicyTagRequest', - 'DeleteTaxonomyRequest', - 'GetPolicyTagRequest', - 'GetTaxonomyRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'PolicyTag', - 'Taxonomy', - 'UpdatePolicyTagRequest', - 'UpdateTaxonomyRequest', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - 'ImportTaxonomiesRequest', - 'ImportTaxonomiesResponse', - 'InlineSource', - 'SerializedPolicyTag', - 'SerializedTaxonomy', - 'ColumnSchema', - 'Schema', - 'SearchCatalogResult', - 'SearchResultType', - 'BigQueryDateShardedSpec', - 'BigQueryTableSpec', - 'TableSpec', - 'ViewSpec', - 'TableSourceType', - 'FieldType', - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'SystemTimestamps', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py deleted file mode 100644 index 8d0def72..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/common.py +++ /dev/null @@ -1,36 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'IntegratedSystem', - }, -) - - -class IntegratedSystem(proto.Enum): - r"""This enum describes all the possible systems that Data - Catalog integrates with. - """ - INTEGRATED_SYSTEM_UNSPECIFIED = 0 - BIGQUERY = 1 - CLOUD_PUBSUB = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py deleted file mode 100644 index 9b3cf03e..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/datacatalog.py +++ /dev/null @@ -1,1225 +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.datacatalog_v1beta1.types import common -from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec as gcd_gcs_fileset_spec -from google.cloud.datacatalog_v1beta1.types import schema as gcd_schema -from google.cloud.datacatalog_v1beta1.types import search -from google.cloud.datacatalog_v1beta1.types import table_spec -from google.cloud.datacatalog_v1beta1.types import tags as gcd_tags -from google.cloud.datacatalog_v1beta1.types import timestamps -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'EntryType', - 'SearchCatalogRequest', - 'SearchCatalogResponse', - 'CreateEntryGroupRequest', - 'UpdateEntryGroupRequest', - 'GetEntryGroupRequest', - 'DeleteEntryGroupRequest', - 'ListEntryGroupsRequest', - 'ListEntryGroupsResponse', - 'CreateEntryRequest', - 'UpdateEntryRequest', - 'DeleteEntryRequest', - 'GetEntryRequest', - 'LookupEntryRequest', - 'Entry', - 'EntryGroup', - 'CreateTagTemplateRequest', - 'GetTagTemplateRequest', - 'UpdateTagTemplateRequest', - 'DeleteTagTemplateRequest', - 'CreateTagRequest', - 'UpdateTagRequest', - 'DeleteTagRequest', - 'CreateTagTemplateFieldRequest', - 'UpdateTagTemplateFieldRequest', - 'RenameTagTemplateFieldRequest', - 'DeleteTagTemplateFieldRequest', - 'ListTagsRequest', - 'ListTagsResponse', - 'ListEntriesRequest', - 'ListEntriesResponse', - }, -) - - -class EntryType(proto.Enum): - r"""Entry resources in Data Catalog can be of different types e.g. a - BigQuery Table entry is of type ``TABLE``. This enum describes all - the possible types Data Catalog contains. - """ - ENTRY_TYPE_UNSPECIFIED = 0 - TABLE = 2 - MODEL = 5 - DATA_STREAM = 3 - FILESET = 4 - - -class SearchCatalogRequest(proto.Message): - r"""Request message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - - Attributes: - scope (google.cloud.datacatalog_v1beta1.types.SearchCatalogRequest.Scope): - Required. The scope of this search request. A ``scope`` that - has empty ``include_org_ids``, ``include_project_ids`` AND - false ``include_gcp_public_datasets`` is considered invalid. - Data Catalog will return an error in such a case. - query (str): - Required. The query string in search query syntax. The query - must be non-empty. - - Query strings can be simple as "x" or more qualified as: - - - name:x - - column:x - - description:y - - Note: Query tokens need to have a minimum of 3 characters - for substring matching to work correctly. See `Data Catalog - Search - Syntax `__ - for more information. - page_size (int): - Number of results in the search page. If <=0 then defaults - to 10. Max limit for page_size is 1000. Throws an invalid - argument for page_size > 1000. - page_token (str): - Optional. Pagination token returned in an earlier - [SearchCatalogResponse.next_page_token][google.cloud.datacatalog.v1beta1.SearchCatalogResponse.next_page_token], - which indicates that this is a continuation of a prior - [SearchCatalogRequest][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog] - call, and that the system should return the next page of - data. If empty, the first page is returned. - order_by (str): - Specifies the ordering of results, currently supported - case-sensitive choices are: - - - ``relevance``, only supports descending - - ``last_modified_timestamp [asc|desc]``, defaults to - descending if not specified - - If not specified, defaults to ``relevance`` descending. - """ - - class Scope(proto.Message): - r"""The criteria that select the subspace used for query - matching. - - Attributes: - include_org_ids (Sequence[str]): - The list of organization IDs to search - within. To find your organization ID, follow - instructions in - https://cloud.google.com/resource- - manager/docs/creating-managing-organization. - include_project_ids (Sequence[str]): - The list of project IDs to search within. To - learn more about the distinction between project - names/IDs/numbers, go to - https://cloud.google.com/docs/overview/#projects. - include_gcp_public_datasets (bool): - If ``true``, include Google Cloud Platform (GCP) public - datasets in the search results. Info on GCP public datasets - is available at https://cloud.google.com/public-datasets/. - By default, GCP public datasets are excluded. - """ - - include_org_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - include_project_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - include_gcp_public_datasets = proto.Field( - proto.BOOL, - number=7, - ) - - scope = proto.Field( - proto.MESSAGE, - number=6, - message=Scope, - ) - query = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - order_by = proto.Field( - proto.STRING, - number=5, - ) - - -class SearchCatalogResponse(proto.Message): - r"""Response message for - [SearchCatalog][google.cloud.datacatalog.v1beta1.DataCatalog.SearchCatalog]. - - Attributes: - results (Sequence[google.cloud.datacatalog_v1beta1.types.SearchCatalogResult]): - Search results. - next_page_token (str): - The token that can be used to retrieve the - next page of results. - """ - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=search.SearchCatalogResult, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateEntryGroupRequest(proto.Message): - r"""Request message for - [CreateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntryGroup]. - - Attributes: - parent (str): - Required. The name of the project this entry group is in. - Example: - - - projects/{project_id}/locations/{location} - - Note that this EntryGroup and its child resources may not - actually be stored in the location in this name. - entry_group_id (str): - Required. The id of the entry group to - create. The id must begin with a letter or - underscore, contain only English letters, - numbers and underscores, and be at most 64 - characters. - entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): - The entry group to create. Defaults to an - empty entry group. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entry_group_id = proto.Field( - proto.STRING, - number=3, - ) - entry_group = proto.Field( - proto.MESSAGE, - number=2, - message='EntryGroup', - ) - - -class UpdateEntryGroupRequest(proto.Message): - r"""Request message for - [UpdateEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntryGroup]. - - Attributes: - entry_group (google.cloud.datacatalog_v1beta1.types.EntryGroup): - Required. The updated entry group. "name" - field must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the entry group. If - absent or empty, all modifiable fields are - updated. - """ - - entry_group = proto.Field( - proto.MESSAGE, - number=1, - message='EntryGroup', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEntryGroupRequest(proto.Message): - r"""Request message for - [GetEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntryGroup]. - - Attributes: - name (str): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return. If not set or empty, - all fields are returned. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntryGroupRequest(proto.Message): - r"""Request message for - [DeleteEntryGroup][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntryGroup]. - - Attributes: - name (str): - Required. The name of the entry group. For example, - ``projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}``. - force (bool): - Optional. If true, deletes all entries in the - entry group. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListEntryGroupsRequest(proto.Message): - r"""Request message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - - Attributes: - parent (str): - Required. The name of the location that contains the entry - groups, which can be provided in URL format. Example: - - - projects/{project_id}/locations/{location} - page_size (int): - Optional. The maximum number of items to return. Default is - 10. Max limit is 1000. Throws an invalid argument for - ``page_size > 1000``. - page_token (str): - Optional. Token that specifies which page is - requested. If empty, the first page is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEntryGroupsResponse(proto.Message): - r"""Response message for - [ListEntryGroups][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntryGroups]. - - Attributes: - entry_groups (Sequence[google.cloud.datacatalog_v1beta1.types.EntryGroup]): - EntryGroup details. - next_page_token (str): - Token to retrieve the next page of results. - It is set to empty if no items remain in - results. - """ - - @property - def raw_page(self): - return self - - entry_groups = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntryGroup', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateEntryRequest(proto.Message): - r"""Request message for - [CreateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.CreateEntry]. - - Attributes: - parent (str): - Required. The name of the entry group this entry is in. - Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - Note that this Entry and its child resources may not - actually be stored in the location in this name. - entry_id (str): - Required. The id of the entry to create. - entry (google.cloud.datacatalog_v1beta1.types.Entry): - Required. The entry to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - entry_id = proto.Field( - proto.STRING, - number=3, - ) - entry = proto.Field( - proto.MESSAGE, - number=2, - message='Entry', - ) - - -class UpdateEntryRequest(proto.Message): - r"""Request message for - [UpdateEntry][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateEntry]. - - Attributes: - entry (google.cloud.datacatalog_v1beta1.types.Entry): - Required. The updated entry. The "name" field - must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the entry. If absent or empty, all - modifiable fields are updated. - - The following fields are modifiable: - - - For entries with type ``DATA_STREAM``: - - - ``schema`` - - - For entries with type ``FILESET`` - - - ``schema`` - - ``display_name`` - - ``description`` - - ``gcs_fileset_spec`` - - ``gcs_fileset_spec.file_patterns`` - - - For entries with ``user_specified_type`` - - - ``schema`` - - ``display_name`` - - ``description`` - - user_specified_type - - user_specified_system - - linked_resource - - source_system_timestamps - """ - - entry = proto.Field( - proto.MESSAGE, - number=1, - message='Entry', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntryRequest(proto.Message): - r"""Request message for - [DeleteEntry][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteEntry]. - - Attributes: - name (str): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEntryRequest(proto.Message): - r"""Request message for - [GetEntry][google.cloud.datacatalog.v1beta1.DataCatalog.GetEntry]. - - Attributes: - name (str): - Required. The name of the entry. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LookupEntryRequest(proto.Message): - r"""Request message for - [LookupEntry][google.cloud.datacatalog.v1beta1.DataCatalog.LookupEntry]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - linked_resource (str): - The full name of the Google Cloud Platform resource the Data - Catalog entry represents. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name. - Full names are case-sensitive. - - Examples: - - - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId - - //pubsub.googleapis.com/projects/projectId/topics/topicId - This field is a member of `oneof`_ ``target_name``. - sql_resource (str): - The SQL name of the entry. SQL names are case-sensitive. - - Examples: - - - ``pubsub.project_id.topic_id`` - - :literal:`pubsub.project_id.`topic.id.with.dots\`` - - ``bigquery.table.project_id.dataset_id.table_id`` - - ``bigquery.dataset.project_id.dataset_id`` - - ``datacatalog.entry.project_id.location_id.entry_group_id.entry_id`` - - ``*_id``\ s shoud satisfy the standard SQL rules for - identifiers. - https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. - This field is a member of `oneof`_ ``target_name``. - """ - - linked_resource = proto.Field( - proto.STRING, - number=1, - oneof='target_name', - ) - sql_resource = proto.Field( - proto.STRING, - number=3, - oneof='target_name', - ) - - -class Entry(proto.Message): - r"""Entry Metadata. A Data Catalog Entry resource represents another - resource in Google Cloud Platform (such as a BigQuery dataset or a - Pub/Sub topic), or outside of Google Cloud Platform. Clients can use - the ``linked_resource`` field in the Entry resource to refer to the - original resource ID of the source system. - - An Entry resource contains resource details, such as its schema. An - Entry can also be used to attach flexible metadata, such as a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The Data Catalog resource name of the entry in URL format. - Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - - Note that this Entry and its child resources may not - actually be stored in the location in this name. - linked_resource (str): - The resource this metadata entry refers to. - - For Google Cloud Platform resources, ``linked_resource`` is - the `full name of the - resource `__. - For example, the ``linked_resource`` for a table resource - from BigQuery is: - - - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId - - Output only when Entry is of type in the EntryType enum. For - entries with user_specified_type, this field is optional and - defaults to an empty string. - type_ (google.cloud.datacatalog_v1beta1.types.EntryType): - The type of the entry. - Only used for Entries with types in the - EntryType enum. - This field is a member of `oneof`_ ``entry_type``. - user_specified_type (str): - Entry type if it does not fit any of the input-allowed - values listed in ``EntryType`` enum above. When creating an - entry, users should check the enum values first, if nothing - matches the entry to be created, then provide a custom - value, for example "my_special_type". - ``user_specified_type`` strings must begin with a letter or - underscore and can only contain letters, numbers, and - underscores; are case insensitive; must be at least 1 - character and at most 64 characters long. - - Currently, only FILESET enum value is allowed. All other - entries created through Data Catalog must use - ``user_specified_type``. - This field is a member of `oneof`_ ``entry_type``. - integrated_system (google.cloud.datacatalog_v1beta1.types.IntegratedSystem): - Output only. This field indicates the entry's - source system that Data Catalog integrates with, - such as BigQuery or Pub/Sub. - This field is a member of `oneof`_ ``system``. - user_specified_system (str): - This field indicates the entry's source system that Data - Catalog does not integrate with. ``user_specified_system`` - strings must begin with a letter or underscore and can only - contain letters, numbers, and underscores; are case - insensitive; must be at least 1 character and at most 64 - characters long. - This field is a member of `oneof`_ ``system``. - gcs_fileset_spec (google.cloud.datacatalog_v1beta1.types.GcsFilesetSpec): - Specification that applies to a Cloud Storage - fileset. This is only valid on entries of type - FILESET. - This field is a member of `oneof`_ ``type_spec``. - bigquery_table_spec (google.cloud.datacatalog_v1beta1.types.BigQueryTableSpec): - Specification that applies to a BigQuery table. This is only - valid on entries of type ``TABLE``. - This field is a member of `oneof`_ ``type_spec``. - bigquery_date_sharded_spec (google.cloud.datacatalog_v1beta1.types.BigQueryDateShardedSpec): - Specification for a group of BigQuery tables with name - pattern ``[prefix]YYYYMMDD``. Context: - https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. - This field is a member of `oneof`_ ``type_spec``. - display_name (str): - Display information such as title and - description. A short name to identify the entry, - for example, "Analytics Data - Jan 2011". - Default value is an empty string. - description (str): - Entry description, which can consist of - several sentences or paragraphs that describe - entry contents. Default value is an empty - string. - schema (google.cloud.datacatalog_v1beta1.types.Schema): - Schema of the entry. An entry might not have - any schema attached to it. - source_system_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): - Output only. Timestamps about the underlying resource, not - about this Data Catalog entry. Output only when Entry is of - type in the EntryType enum. For entries with - user_specified_type, this field is optional and defaults to - an empty timestamp. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - linked_resource = proto.Field( - proto.STRING, - number=9, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - oneof='entry_type', - enum='EntryType', - ) - user_specified_type = proto.Field( - proto.STRING, - number=16, - oneof='entry_type', - ) - integrated_system = proto.Field( - proto.ENUM, - number=17, - oneof='system', - enum=common.IntegratedSystem, - ) - user_specified_system = proto.Field( - proto.STRING, - number=18, - oneof='system', - ) - gcs_fileset_spec = proto.Field( - proto.MESSAGE, - number=6, - oneof='type_spec', - message=gcd_gcs_fileset_spec.GcsFilesetSpec, - ) - bigquery_table_spec = proto.Field( - proto.MESSAGE, - number=12, - oneof='type_spec', - message=table_spec.BigQueryTableSpec, - ) - bigquery_date_sharded_spec = proto.Field( - proto.MESSAGE, - number=15, - oneof='type_spec', - message=table_spec.BigQueryDateShardedSpec, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - schema = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_schema.Schema, - ) - source_system_timestamps = proto.Field( - proto.MESSAGE, - number=7, - message=timestamps.SystemTimestamps, - ) - - -class EntryGroup(proto.Message): - r"""EntryGroup Metadata. An EntryGroup resource represents a logical - grouping of zero or more Data Catalog - [Entry][google.cloud.datacatalog.v1beta1.Entry] resources. - - Attributes: - name (str): - The resource name of the entry group in URL format. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - Note that this EntryGroup and its child resources may not - actually be stored in the location in this name. - display_name (str): - A short name to identify the entry group, for - example, "analytics data - jan 2011". Default - value is an empty string. - description (str): - Entry group description, which can consist of - several sentences or paragraphs that describe - entry group contents. Default value is an empty - string. - data_catalog_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): - Output only. Timestamps about this - EntryGroup. Default value is empty timestamps. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - data_catalog_timestamps = proto.Field( - proto.MESSAGE, - number=4, - message=timestamps.SystemTimestamps, - ) - - -class CreateTagTemplateRequest(proto.Message): - r"""Request message for - [CreateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplate]. - - Attributes: - parent (str): - Required. The name of the project and the template location - [region](https://cloud.google.com/data-catalog/docs/concepts/regions. - - Example: - - - projects/{project_id}/locations/us-central1 - tag_template_id (str): - Required. The id of the tag template to - create. - tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): - Required. The tag template to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag_template_id = proto.Field( - proto.STRING, - number=3, - ) - tag_template = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.TagTemplate, - ) - - -class GetTagTemplateRequest(proto.Message): - r"""Request message for - [GetTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.GetTagTemplate]. - - Attributes: - name (str): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateTagTemplateRequest(proto.Message): - r"""Request message for - [UpdateTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplate]. - - Attributes: - tag_template (google.cloud.datacatalog_v1beta1.types.TagTemplate): - Required. The template to update. The "name" - field must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The field mask specifies the parts of the template to - overwrite. - - Allowed fields: - - - ``display_name`` - - If absent or empty, all of the allowed fields above will be - updated. - """ - - tag_template = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_tags.TagTemplate, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteTagTemplateRequest(proto.Message): - r"""Request message for - [DeleteTagTemplate][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplate]. - - Attributes: - name (str): - Required. The name of the tag template to delete. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - force (bool): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of any possible tags - using this template. ``force = false`` will be supported in - the future. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class CreateTagRequest(proto.Message): - r"""Request message for - [CreateTag][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTag]. - - Attributes: - parent (str): - Required. The name of the resource to attach this tag to. - Tags can be attached to Entries. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - - Note that this Tag and its child resources may not actually - be stored in the location in this name. - tag (google.cloud.datacatalog_v1beta1.types.Tag): - Required. The tag to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.Tag, - ) - - -class UpdateTagRequest(proto.Message): - r"""Request message for - [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. - - Attributes: - tag (google.cloud.datacatalog_v1beta1.types.Tag): - Required. The updated tag. The "name" field - must be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update on the Tag. If absent or empty, all - modifiable fields are updated. Currently the only modifiable - field is the field ``fields``. - """ - - tag = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_tags.Tag, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteTagRequest(proto.Message): - r"""Request message for - [DeleteTag][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTag]. - - Attributes: - name (str): - Required. The name of the tag to delete. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id} - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTagTemplateFieldRequest(proto.Message): - r"""Request message for - [CreateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.CreateTagTemplateField]. - - Attributes: - parent (str): - Required. The name of the project and the template location - `region `__. - - Example: - - - projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id} - tag_template_field_id (str): - Required. The ID of the tag template field to create. Field - ids can contain letters (both uppercase and lowercase), - numbers (0-9), underscores (_) and dashes (-). Field IDs - must be at least 1 character long and at most 128 characters - long. Field IDs must also be unique within their template. - tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): - Required. The tag template field to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - tag_template_field_id = proto.Field( - proto.STRING, - number=2, - ) - tag_template_field = proto.Field( - proto.MESSAGE, - number=3, - message=gcd_tags.TagTemplateField, - ) - - -class UpdateTagTemplateFieldRequest(proto.Message): - r"""Request message for - [UpdateTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template field. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - tag_template_field (google.cloud.datacatalog_v1beta1.types.TagTemplateField): - Required. The template to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The field mask specifies the parts of the template - to be updated. Allowed fields: - - - ``display_name`` - - ``type.enum_type`` - - ``is_required`` - - If ``update_mask`` is not set or empty, all of the allowed - fields above will be updated. - - When updating an enum type, the provided values will be - merged with the existing values. Therefore, enum values can - only be added, existing enum values cannot be deleted nor - renamed. Updating a template field from optional to required - is NOT allowed. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - tag_template_field = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_tags.TagTemplateField, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class RenameTagTemplateFieldRequest(proto.Message): - r"""Request message for - [RenameTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.RenameTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - new_tag_template_field_id (str): - Required. The new ID of this tag template field. For - example, ``my_new_field``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - new_tag_template_field_id = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteTagTemplateFieldRequest(proto.Message): - r"""Request message for - [DeleteTagTemplateField][google.cloud.datacatalog.v1beta1.DataCatalog.DeleteTagTemplateField]. - - Attributes: - name (str): - Required. The name of the tag template field to delete. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id} - force (bool): - Required. Currently, this field must always be set to - ``true``. This confirms the deletion of this field from any - tags using this field. ``force = false`` will be supported - in the future. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListTagsRequest(proto.Message): - r"""Request message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - - Attributes: - parent (str): - Required. The name of the Data Catalog resource to list the - tags of. The resource could be an - [Entry][google.cloud.datacatalog.v1beta1.Entry] or an - [EntryGroup][google.cloud.datacatalog.v1beta1.EntryGroup]. - - Examples: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} - page_size (int): - The maximum number of tags to return. Default - is 10. Max limit is 1000. - page_token (str): - Token that specifies which page is requested. - If empty, the first page is returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTagsResponse(proto.Message): - r"""Response message for - [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags]. - - Attributes: - tags (Sequence[google.cloud.datacatalog_v1beta1.types.Tag]): - [Tag][google.cloud.datacatalog.v1beta1.Tag] details. - next_page_token (str): - Token to retrieve the next page of results. - It is set to empty if no items remain in - results. - """ - - @property - def raw_page(self): - return self - - tags = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_tags.Tag, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEntriesRequest(proto.Message): - r"""Request message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - - Attributes: - parent (str): - Required. The name of the entry group that contains the - entries, which can be provided in URL format. Example: - - - projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} - page_size (int): - The maximum number of items to return. Default is 10. Max - limit is 1000. Throws an invalid argument for - ``page_size > 1000``. - page_token (str): - Token that specifies which page is requested. - If empty, the first page is returned. - read_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to return for each Entry. If not set or empty, - all fields are returned. For example, setting read_mask to - contain only one path "name" will cause ListEntries to - return a list of Entries with only "name" field. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - read_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class ListEntriesResponse(proto.Message): - r"""Response message for - [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries]. - - Attributes: - entries (Sequence[google.cloud.datacatalog_v1beta1.types.Entry]): - Entry details. - next_page_token (str): - Token to retrieve the next page of results. - It is set to empty if no items remain in - results. - """ - - @property - def raw_page(self): - return self - - entries = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Entry', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py deleted file mode 100644 index 713fc6c2..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/gcs_fileset_spec.py +++ /dev/null @@ -1,113 +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.datacatalog_v1beta1.types import timestamps - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'GcsFilesetSpec', - 'GcsFileSpec', - }, -) - - -class GcsFilesetSpec(proto.Message): - r"""Describes a Cloud Storage fileset entry. - - Attributes: - file_patterns (Sequence[str]): - Required. Patterns to identify a set of files in Google - Cloud Storage. See `Cloud Storage - documentation `__ - for more information. Note that bucket wildcards are - currently not supported. - - Examples of valid file_patterns: - - - ``gs://bucket_name/dir/*``: matches all files within - ``bucket_name/dir`` directory. - - ``gs://bucket_name/dir/**``: matches all files in - ``bucket_name/dir`` spanning all subdirectories. - - ``gs://bucket_name/file*``: matches files prefixed by - ``file`` in ``bucket_name`` - - ``gs://bucket_name/??.txt``: matches files with two - characters followed by ``.txt`` in ``bucket_name`` - - ``gs://bucket_name/[aeiou].txt``: matches files that - contain a single vowel character followed by ``.txt`` in - ``bucket_name`` - - ``gs://bucket_name/[a-m].txt``: matches files that - contain ``a``, ``b``, ... or ``m`` followed by ``.txt`` - in ``bucket_name`` - - ``gs://bucket_name/a/*/b``: matches all files in - ``bucket_name`` that match ``a/*/b`` pattern, such as - ``a/c/b``, ``a/d/b`` - - ``gs://another_bucket/a.txt``: matches - ``gs://another_bucket/a.txt`` - - You can combine wildcards to provide more powerful matches, - for example: - - - ``gs://bucket_name/[a-m]??.j*g`` - sample_gcs_file_specs (Sequence[google.cloud.datacatalog_v1beta1.types.GcsFileSpec]): - Output only. Sample files contained in this - fileset, not all files contained in this fileset - are represented here. - """ - - file_patterns = proto.RepeatedField( - proto.STRING, - number=1, - ) - sample_gcs_file_specs = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='GcsFileSpec', - ) - - -class GcsFileSpec(proto.Message): - r"""Specifications of a single file in Cloud Storage. - - Attributes: - file_path (str): - Required. The full file path. Example: - ``gs://bucket_name/a/b.txt``. - gcs_timestamps (google.cloud.datacatalog_v1beta1.types.SystemTimestamps): - Output only. Timestamps about the Cloud - Storage file. - size_bytes (int): - Output only. The size of the file, in bytes. - """ - - file_path = proto.Field( - proto.STRING, - number=1, - ) - gcs_timestamps = proto.Field( - proto.MESSAGE, - number=2, - message=timestamps.SystemTimestamps, - ) - size_bytes = proto.Field( - proto.INT64, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py deleted file mode 100644 index 1721e86c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanager.py +++ /dev/null @@ -1,449 +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 field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'Taxonomy', - 'PolicyTag', - 'CreateTaxonomyRequest', - 'DeleteTaxonomyRequest', - 'UpdateTaxonomyRequest', - 'ListTaxonomiesRequest', - 'ListTaxonomiesResponse', - 'GetTaxonomyRequest', - 'CreatePolicyTagRequest', - 'DeletePolicyTagRequest', - 'UpdatePolicyTagRequest', - 'ListPolicyTagsRequest', - 'ListPolicyTagsResponse', - 'GetPolicyTagRequest', - }, -) - - -class Taxonomy(proto.Message): - r"""A taxonomy is a collection of policy tags that classify data along a - common axis. For instance a data *sensitivity* taxonomy could - contain policy tags denoting PII such as age, zipcode, and SSN. A - data *origin* taxonomy could contain policy tags to distinguish user - data, employee data, partner data, public data. - - Attributes: - name (str): - Output only. Resource name of this taxonomy, whose format - is: - "projects/{project_number}/locations/{location_id}/taxonomies/{id}". - display_name (str): - Required. User defined name of this taxonomy. - It must: contain only unicode letters, numbers, - underscores, dashes and spaces; not start or end - with spaces; and be at most 200 bytes long when - encoded in UTF-8. - description (str): - Optional. Description of this taxonomy. It - must: contain only unicode characters, tabs, - newlines, carriage returns and page breaks; and - be at most 2000 bytes long when encoded in - UTF-8. If not set, defaults to an empty - description. - activated_policy_types (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy.PolicyType]): - Optional. A list of policy types that are - activated for this taxonomy. If not set, - defaults to an empty list. - """ - class PolicyType(proto.Enum): - r"""Defines policy types where policy tag can be used for.""" - POLICY_TYPE_UNSPECIFIED = 0 - FINE_GRAINED_ACCESS_CONTROL = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - activated_policy_types = proto.RepeatedField( - proto.ENUM, - number=6, - enum=PolicyType, - ) - - -class PolicyTag(proto.Message): - r"""Denotes one policy tag in a taxonomy (e.g. ssn). Policy Tags - can be defined in a hierarchy. For example, consider the - following hierarchy: Geolocation -> (LatLong, City, ZipCode). - PolicyTag "Geolocation" contains three child policy tags: - "LatLong", "City", and "ZipCode". - - Attributes: - name (str): - Output only. Resource name of this policy tag, whose format - is: - "projects/{project_number}/locations/{location_id}/taxonomies/{taxonomy_id}/policyTags/{id}". - display_name (str): - Required. User defined name of this policy - tag. It must: be unique within the parent - taxonomy; contain only unicode letters, numbers, - underscores, dashes and spaces; not start or end - with spaces; and be at most 200 bytes long when - encoded in UTF-8. - description (str): - Description of this policy tag. It must: - contain only unicode characters, tabs, newlines, - carriage returns and page breaks; and be at most - 2000 bytes long when encoded in UTF-8. If not - set, defaults to an empty description. If not - set, defaults to an empty description. - parent_policy_tag (str): - Resource name of this policy tag's parent - policy tag (e.g. for the "LatLong" policy tag in - the example above, this field contains the - resource name of the "Geolocation" policy tag). - If empty, it means this policy tag is a top - level policy tag (e.g. this field is empty for - the "Geolocation" policy tag in the example - above). If not set, defaults to an empty string. - child_policy_tags (Sequence[str]): - Output only. Resource names of child policy - tags of this policy tag. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - parent_policy_tag = proto.Field( - proto.STRING, - number=4, - ) - child_policy_tags = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class CreateTaxonomyRequest(proto.Message): - r"""Request message for - [CreateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreateTaxonomy]. - - Attributes: - parent (str): - Required. Resource name of the project that - the taxonomy will belong to. - taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): - The taxonomy to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - taxonomy = proto.Field( - proto.MESSAGE, - number=2, - message='Taxonomy', - ) - - -class DeleteTaxonomyRequest(proto.Message): - r"""Request message for - [DeleteTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeleteTaxonomy]. - - Attributes: - name (str): - Required. Resource name of the taxonomy to be - deleted. All policy tags in this taxonomy will - also be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateTaxonomyRequest(proto.Message): - r"""Request message for - [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. - - Attributes: - taxonomy (google.cloud.datacatalog_v1beta1.types.Taxonomy): - The taxonomy to update. Only description, display_name, and - activated policy types can be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - If not set, defaults to all of the fields that are allowed - to update. - """ - - taxonomy = proto.Field( - proto.MESSAGE, - number=1, - message='Taxonomy', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListTaxonomiesRequest(proto.Message): - r"""Request message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - - Attributes: - parent (str): - Required. Resource name of the project to - list the taxonomies of. - page_size (int): - The maximum number of items to return. Must - be a value between 1 and 1000. If not set, - defaults to 50. - page_token (str): - The next_page_token value returned from a previous list - request, if any. If not set, defaults to an empty string. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTaxonomiesResponse(proto.Message): - r"""Response message for - [ListTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy]): - Taxonomies that the project contains. - next_page_token (str): - Token used to retrieve the next page of - results, or empty if there are no more results - in the list. - """ - - @property - def raw_page(self): - return self - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Taxonomy', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTaxonomyRequest(proto.Message): - r"""Request message for - [GetTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetTaxonomy]. - - Attributes: - name (str): - Required. Resource name of the requested - taxonomy. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreatePolicyTagRequest(proto.Message): - r"""Request message for - [CreatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.CreatePolicyTag]. - - Attributes: - parent (str): - Required. Resource name of the taxonomy that - the policy tag will belong to. - policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): - The policy tag to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - policy_tag = proto.Field( - proto.MESSAGE, - number=2, - message='PolicyTag', - ) - - -class DeletePolicyTagRequest(proto.Message): - r"""Request message for - [DeletePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.DeletePolicyTag]. - - Attributes: - name (str): - Required. Resource name of the policy tag to - be deleted. All of its descendant policy tags - will also be deleted. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdatePolicyTagRequest(proto.Message): - r"""Request message for - [UpdatePolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdatePolicyTag]. - - Attributes: - policy_tag (google.cloud.datacatalog_v1beta1.types.PolicyTag): - The policy tag to update. Only the description, - display_name, and parent_policy_tag fields can be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The update mask applies to the resource. Only display_name, - description and parent_policy_tag can be updated and thus - can be listed in the mask. If update_mask is not provided, - all allowed fields (i.e. display_name, description and - parent) will be updated. For more information including the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - If not set, defaults to all of the fields that are allowed - to update. - """ - - policy_tag = proto.Field( - proto.MESSAGE, - number=1, - message='PolicyTag', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListPolicyTagsRequest(proto.Message): - r"""Request message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - - Attributes: - parent (str): - Required. Resource name of the taxonomy to - list the policy tags of. - page_size (int): - The maximum number of items to return. Must - be a value between 1 and 1000. If not set, - defaults to 50. - page_token (str): - The next_page_token value returned from a previous List - request, if any. If not set, defaults to an empty string. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListPolicyTagsResponse(proto.Message): - r"""Response message for - [ListPolicyTags][google.cloud.datacatalog.v1beta1.PolicyTagManager.ListPolicyTags]. - - Attributes: - policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.PolicyTag]): - The policy tags that are in the requested - taxonomy. - next_page_token (str): - Token used to retrieve the next page of - results, or empty if there are no more results - in the list. - """ - - @property - def raw_page(self): - return self - - policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PolicyTag', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPolicyTagRequest(proto.Message): - r"""Request message for - [GetPolicyTag][google.cloud.datacatalog.v1beta1.PolicyTagManager.GetPolicyTag]. - - Attributes: - name (str): - Required. Resource name of the requested - policy tag. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py deleted file mode 100644 index efe0aefd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py +++ /dev/null @@ -1,210 +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.datacatalog_v1beta1.types import policytagmanager - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'SerializedTaxonomy', - 'SerializedPolicyTag', - 'ImportTaxonomiesRequest', - 'InlineSource', - 'ImportTaxonomiesResponse', - 'ExportTaxonomiesRequest', - 'ExportTaxonomiesResponse', - }, -) - - -class SerializedTaxonomy(proto.Message): - r"""Message capturing a taxonomy and its policy tag hierarchy as - a nested proto. Used for taxonomy import/export and mutation. - - Attributes: - display_name (str): - Required. Display name of the taxonomy. Max - 200 bytes when encoded in UTF-8. - description (str): - Description of the serialized taxonomy. The - length of the description is limited to 2000 - bytes when encoded in UTF-8. If not set, - defaults to an empty description. - policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedPolicyTag]): - Top level policy tags associated with the - taxonomy if any. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='SerializedPolicyTag', - ) - - -class SerializedPolicyTag(proto.Message): - r"""Message representing one policy tag when exported as a nested - proto. - - Attributes: - display_name (str): - Required. Display name of the policy tag. Max - 200 bytes when encoded in UTF-8. - description (str): - Description of the serialized policy tag. The - length of the description is limited to 2000 - bytes when encoded in UTF-8. If not set, - defaults to an empty description. - child_policy_tags (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedPolicyTag]): - Children of the policy tag if any. - """ - - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - child_policy_tags = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SerializedPolicyTag', - ) - - -class ImportTaxonomiesRequest(proto.Message): - r"""Request message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Resource name of project that the - newly created taxonomies will belong to. - inline_source (google.cloud.datacatalog_v1beta1.types.InlineSource): - Inline source used for taxonomies import - This field is a member of `oneof`_ ``source``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - inline_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='InlineSource', - ) - - -class InlineSource(proto.Message): - r"""Inline source used for taxonomies import. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedTaxonomy]): - Required. Taxonomies to be imported. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SerializedTaxonomy', - ) - - -class ImportTaxonomiesResponse(proto.Message): - r"""Response message for - [ImportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ImportTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.Taxonomy]): - Taxonomies that were imported. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=policytagmanager.Taxonomy, - ) - - -class ExportTaxonomiesRequest(proto.Message): - r"""Request message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Resource name of the project that - taxonomies to be exported will share. - taxonomies (Sequence[str]): - Required. Resource names of the taxonomies to - be exported. - serialized_taxonomies (bool): - Export taxonomies as serialized taxonomies. - This field is a member of `oneof`_ ``destination``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - taxonomies = proto.RepeatedField( - proto.STRING, - number=2, - ) - serialized_taxonomies = proto.Field( - proto.BOOL, - number=3, - oneof='destination', - ) - - -class ExportTaxonomiesResponse(proto.Message): - r"""Response message for - [ExportTaxonomies][google.cloud.datacatalog.v1beta1.PolicyTagManagerSerialization.ExportTaxonomies]. - - Attributes: - taxonomies (Sequence[google.cloud.datacatalog_v1beta1.types.SerializedTaxonomy]): - List of taxonomies and policy tags in a tree - structure. - """ - - taxonomies = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SerializedTaxonomy', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py deleted file mode 100644 index ebd9763d..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/schema.py +++ /dev/null @@ -1,89 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'Schema', - 'ColumnSchema', - }, -) - - -class Schema(proto.Message): - r"""Represents a schema (e.g. BigQuery, GoogleSQL, Avro schema). - - Attributes: - columns (Sequence[google.cloud.datacatalog_v1beta1.types.ColumnSchema]): - Required. Schema of columns. A maximum of - 10,000 columns and sub-columns can be specified. - """ - - columns = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ColumnSchema', - ) - - -class ColumnSchema(proto.Message): - r"""Representation of a column within a schema. Columns could be - nested inside other columns. - - Attributes: - column (str): - Required. Name of the column. - type_ (str): - Required. Type of the column. - description (str): - Optional. Description of the column. Default - value is an empty string. - mode (str): - Optional. A column's mode indicates whether the values in - this column are required, nullable, etc. Only ``NULLABLE``, - ``REQUIRED`` and ``REPEATED`` are supported. Default mode is - ``NULLABLE``. - subcolumns (Sequence[google.cloud.datacatalog_v1beta1.types.ColumnSchema]): - Optional. Schema of sub-columns. A column can - have zero or more sub-columns. - """ - - column = proto.Field( - proto.STRING, - number=6, - ) - type_ = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - mode = proto.Field( - proto.STRING, - number=3, - ) - subcolumns = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ColumnSchema', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py deleted file mode 100644 index 7ec09b85..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/search.py +++ /dev/null @@ -1,88 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'SearchResultType', - 'SearchCatalogResult', - }, -) - - -class SearchResultType(proto.Enum): - r"""The different types of resources that can be returned in - search. - """ - SEARCH_RESULT_TYPE_UNSPECIFIED = 0 - ENTRY = 1 - TAG_TEMPLATE = 2 - ENTRY_GROUP = 3 - - -class SearchCatalogResult(proto.Message): - r"""A result that appears in the response of a search request. - Each result captures details of one entry that matches the - search. - - Attributes: - search_result_type (google.cloud.datacatalog_v1beta1.types.SearchResultType): - Type of the search result. This field can be - used to determine which Get method to call to - fetch the full resource. - search_result_subtype (str): - Sub-type of the search result. This is a dot-delimited - description of the resource's full type, and is the same as - the value callers would provide in the "type" search facet. - Examples: ``entry.table``, ``entry.dataStream``, - ``tagTemplate``. - relative_resource_name (str): - The relative resource name of the resource in URL format. - Examples: - - - ``projects/{project_id}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}`` - - ``projects/{project_id}/tagTemplates/{tag_template_id}`` - linked_resource (str): - The full name of the cloud resource the entry belongs to. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name. - Example: - - - ``//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId`` - """ - - search_result_type = proto.Field( - proto.ENUM, - number=1, - enum='SearchResultType', - ) - search_result_subtype = proto.Field( - proto.STRING, - number=2, - ) - relative_resource_name = proto.Field( - proto.STRING, - number=3, - ) - linked_resource = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py deleted file mode 100644 index 3c903a50..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/table_spec.py +++ /dev/null @@ -1,147 +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 - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'TableSourceType', - 'BigQueryTableSpec', - 'ViewSpec', - 'TableSpec', - 'BigQueryDateShardedSpec', - }, -) - - -class TableSourceType(proto.Enum): - r"""Table source type.""" - TABLE_SOURCE_TYPE_UNSPECIFIED = 0 - BIGQUERY_VIEW = 2 - BIGQUERY_TABLE = 5 - - -class BigQueryTableSpec(proto.Message): - r"""Describes a BigQuery table. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - table_source_type (google.cloud.datacatalog_v1beta1.types.TableSourceType): - Output only. The table source type. - view_spec (google.cloud.datacatalog_v1beta1.types.ViewSpec): - Table view specification. This field should only be - populated if ``table_source_type`` is ``BIGQUERY_VIEW``. - This field is a member of `oneof`_ ``type_spec``. - table_spec (google.cloud.datacatalog_v1beta1.types.TableSpec): - Spec of a BigQuery table. This field should only be - populated if ``table_source_type`` is ``BIGQUERY_TABLE``. - This field is a member of `oneof`_ ``type_spec``. - """ - - table_source_type = proto.Field( - proto.ENUM, - number=1, - enum='TableSourceType', - ) - view_spec = proto.Field( - proto.MESSAGE, - number=2, - oneof='type_spec', - message='ViewSpec', - ) - table_spec = proto.Field( - proto.MESSAGE, - number=3, - oneof='type_spec', - message='TableSpec', - ) - - -class ViewSpec(proto.Message): - r"""Table view specification. - - Attributes: - view_query (str): - Output only. The query that defines the table - view. - """ - - view_query = proto.Field( - proto.STRING, - number=1, - ) - - -class TableSpec(proto.Message): - r"""Normal BigQuery table spec. - - Attributes: - grouped_entry (str): - Output only. If the table is a dated shard, i.e., with name - pattern ``[prefix]YYYYMMDD``, ``grouped_entry`` is the Data - Catalog resource name of the date sharded grouped entry, for - example, - ``projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}``. - Otherwise, ``grouped_entry`` is empty. - """ - - grouped_entry = proto.Field( - proto.STRING, - number=1, - ) - - -class BigQueryDateShardedSpec(proto.Message): - r"""Spec for a group of BigQuery tables with name pattern - ``[prefix]YYYYMMDD``. Context: - https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding - - Attributes: - dataset (str): - Output only. The Data Catalog resource name of the dataset - entry the current table belongs to, for example, - ``projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}``. - table_prefix (str): - Output only. The table name prefix of the shards. The name - of any given shard is ``[table_prefix]YYYYMMDD``, for - example, for shard ``MyTable20180101``, the ``table_prefix`` - is ``MyTable``. - shard_count (int): - Output only. Total number of shards. - """ - - dataset = proto.Field( - proto.STRING, - number=1, - ) - table_prefix = proto.Field( - proto.STRING, - number=2, - ) - shard_count = proto.Field( - proto.INT64, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py deleted file mode 100644 index 62076ed0..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/tags.py +++ /dev/null @@ -1,384 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'Tag', - 'TagField', - 'TagTemplate', - 'TagTemplateField', - 'FieldType', - }, -) - - -class Tag(proto.Message): - r"""Tags are used to attach custom metadata to Data Catalog resources. - Tags conform to the specifications within their tag template. - - See `Data Catalog - IAM `__ for - information on the permissions needed to create or view tags. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the tag in URL format. Example: - - - projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id} - - where ``tag_id`` is a system-generated identifier. Note that - this Tag may not actually be stored in the location in this - name. - template (str): - Required. The resource name of the tag template that this - tag uses. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - - This field cannot be modified after creation. - template_display_name (str): - Output only. The display name of the tag - template. - column (str): - Resources like Entry can have schemas associated with them. - This scope allows users to attach tags to an individual - column based on that schema. - - For attaching a tag to a nested column, use ``.`` to - separate the column names. Example: - - - ``outer_column.inner_column`` - This field is a member of `oneof`_ ``scope``. - fields (Sequence[google.cloud.datacatalog_v1beta1.types.Tag.FieldsEntry]): - Required. This maps the ID of a tag field to - the value of and additional information about - that field. Valid field IDs are defined by the - tag's template. A tag must have at least 1 field - and at most 500 fields. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - template = proto.Field( - proto.STRING, - number=2, - ) - template_display_name = proto.Field( - proto.STRING, - number=5, - ) - column = proto.Field( - proto.STRING, - number=4, - oneof='scope', - ) - fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='TagField', - ) - - -class TagField(proto.Message): - r"""Contains the value and supporting information for a field within a - [Tag][google.cloud.datacatalog.v1beta1.Tag]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - display_name (str): - Output only. The display name of this field. - double_value (float): - Holds the value for a tag field with double - type. - This field is a member of `oneof`_ ``kind``. - string_value (str): - Holds the value for a tag field with string - type. - This field is a member of `oneof`_ ``kind``. - bool_value (bool): - Holds the value for a tag field with boolean - type. - This field is a member of `oneof`_ ``kind``. - timestamp_value (google.protobuf.timestamp_pb2.Timestamp): - Holds the value for a tag field with - timestamp type. - This field is a member of `oneof`_ ``kind``. - enum_value (google.cloud.datacatalog_v1beta1.types.TagField.EnumValue): - Holds the value for a tag field with enum - type. This value must be one of the allowed - values in the definition of this enum. - This field is a member of `oneof`_ ``kind``. - order (int): - Output only. The order of this field with respect to other - fields in this tag. It can be set in - [Tag][google.cloud.datacatalog.v1beta1.TagTemplateField.order]. - For example, a higher value can indicate a more important - field. The value can be negative. Multiple fields can have - the same order, and field orders within a tag do not have to - be sequential. - """ - - class EnumValue(proto.Message): - r"""Holds an enum value. - - Attributes: - display_name (str): - The display name of the enum value. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - - display_name = proto.Field( - proto.STRING, - number=1, - ) - double_value = proto.Field( - proto.DOUBLE, - number=2, - oneof='kind', - ) - string_value = proto.Field( - proto.STRING, - number=3, - oneof='kind', - ) - bool_value = proto.Field( - proto.BOOL, - number=4, - oneof='kind', - ) - timestamp_value = proto.Field( - proto.MESSAGE, - number=5, - oneof='kind', - message=timestamp_pb2.Timestamp, - ) - enum_value = proto.Field( - proto.MESSAGE, - number=6, - oneof='kind', - message=EnumValue, - ) - order = proto.Field( - proto.INT32, - number=7, - ) - - -class TagTemplate(proto.Message): - r"""A tag template defines a tag, which can have one or more typed - fields. The template is used to create and attach the tag to GCP - resources. `Tag template - roles `__ - provide permissions to create, edit, and use the template. See, for - example, the `TagTemplate - User `__ - role, which includes permission to use the tag template to tag - resources. - - Attributes: - name (str): - The resource name of the tag template in URL format. - Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id} - - Note that this TagTemplate and its child resources may not - actually be stored in the location in this name. - display_name (str): - The display name for this template. Defaults - to an empty string. - fields (Sequence[google.cloud.datacatalog_v1beta1.types.TagTemplate.FieldsEntry]): - Required. Map of tag template field IDs to the settings for - the field. This map is an exhaustive list of the allowed - fields. This map must contain at least one field and at most - 500 fields. - - The keys to this map are tag template field IDs. Field IDs - can contain letters (both uppercase and lowercase), numbers - (0-9) and underscores (_). Field IDs must be at least 1 - character long and at most 64 characters long. Field IDs - must start with a letter or underscore. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - fields = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='TagTemplateField', - ) - - -class TagTemplateField(proto.Message): - r"""The template for an individual field within a tag template. - - Attributes: - name (str): - Output only. The resource name of the tag template field in - URL format. Example: - - - projects/{project_id}/locations/{location}/tagTemplates/{tag_template}/fields/{field} - - Note that this TagTemplateField may not actually be stored - in the location in this name. - display_name (str): - The display name for this field. Defaults to - an empty string. - type_ (google.cloud.datacatalog_v1beta1.types.FieldType): - Required. The type of value this tag field - can contain. - is_required (bool): - Whether this is a required field. Defaults to - false. - order (int): - The order of this field with respect to other - fields in this tag template. A higher value - indicates a more important field. The value can - be negative. Multiple fields can have the same - order, and field orders within a tag do not have - to be sequential. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - display_name = proto.Field( - proto.STRING, - number=1, - ) - type_ = proto.Field( - proto.MESSAGE, - number=2, - message='FieldType', - ) - is_required = proto.Field( - proto.BOOL, - number=3, - ) - order = proto.Field( - proto.INT32, - number=5, - ) - - -class FieldType(proto.Message): - r""" - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - primitive_type (google.cloud.datacatalog_v1beta1.types.FieldType.PrimitiveType): - Represents primitive types - string, bool - etc. - This field is a member of `oneof`_ ``type_decl``. - enum_type (google.cloud.datacatalog_v1beta1.types.FieldType.EnumType): - Represents an enum type. - This field is a member of `oneof`_ ``type_decl``. - """ - class PrimitiveType(proto.Enum): - r"""""" - PRIMITIVE_TYPE_UNSPECIFIED = 0 - DOUBLE = 1 - STRING = 2 - BOOL = 3 - TIMESTAMP = 4 - - class EnumType(proto.Message): - r""" - - Attributes: - allowed_values (Sequence[google.cloud.datacatalog_v1beta1.types.FieldType.EnumType.EnumValue]): - Required on create; optional on update. The - set of allowed values for this enum. This set - must not be empty, the display names of the - values in this set must not be empty and the - display names of the values must be case- - insensitively unique within this set. Currently, - enum values can only be added to the list of - allowed values. Deletion and renaming of enum - values are not supported. Can have up to 500 - allowed values. - """ - - class EnumValue(proto.Message): - r""" - - Attributes: - display_name (str): - Required. The display name of the enum value. - Must not be an empty string. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - - allowed_values = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FieldType.EnumType.EnumValue', - ) - - primitive_type = proto.Field( - proto.ENUM, - number=1, - oneof='type_decl', - enum=PrimitiveType, - ) - enum_type = proto.Field( - proto.MESSAGE, - number=2, - oneof='type_decl', - message=EnumType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py b/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py deleted file mode 100644 index fc53ac2c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/datacatalog_v1beta1/types/timestamps.py +++ /dev/null @@ -1,63 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.datacatalog.v1beta1', - manifest={ - 'SystemTimestamps', - }, -) - - -class SystemTimestamps(proto.Message): - r"""Timestamps about this resource according to a particular - system. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the resource within the - given system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last-modified time of the resource within - the given system. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The expiration time of the - resource within the given system. Currently only - apllicable to BigQuery resources. - """ - - create_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py deleted file mode 100644 index eb1e18c1..00000000 --- a/owl-bot-staging/v1beta1/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', '3.10']) -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/datacatalog_v1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.9') -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', '3.8', '3.9']) -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.9') -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/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py deleted file mode 100644 index f67585cf..00000000 --- a/owl-bot-staging/v1beta1/scripts/fixup_datacatalog_v1beta1_keywords.py +++ /dev/null @@ -1,214 +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 datacatalogCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_entry': ('parent', 'entry_id', 'entry', ), - 'create_entry_group': ('parent', 'entry_group_id', 'entry_group', ), - 'create_policy_tag': ('parent', 'policy_tag', ), - 'create_tag': ('parent', 'tag', ), - 'create_tag_template': ('parent', 'tag_template_id', 'tag_template', ), - 'create_tag_template_field': ('parent', 'tag_template_field_id', 'tag_template_field', ), - 'create_taxonomy': ('parent', 'taxonomy', ), - 'delete_entry': ('name', ), - 'delete_entry_group': ('name', 'force', ), - 'delete_policy_tag': ('name', ), - 'delete_tag': ('name', ), - 'delete_tag_template': ('name', 'force', ), - 'delete_tag_template_field': ('name', 'force', ), - 'delete_taxonomy': ('name', ), - 'export_taxonomies': ('parent', 'taxonomies', 'serialized_taxonomies', ), - 'get_entry': ('name', ), - 'get_entry_group': ('name', 'read_mask', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_policy_tag': ('name', ), - 'get_tag_template': ('name', ), - 'get_taxonomy': ('name', ), - 'import_taxonomies': ('parent', 'inline_source', ), - 'list_entries': ('parent', 'page_size', 'page_token', 'read_mask', ), - 'list_entry_groups': ('parent', 'page_size', 'page_token', ), - 'list_policy_tags': ('parent', 'page_size', 'page_token', ), - 'list_tags': ('parent', 'page_size', 'page_token', ), - 'list_taxonomies': ('parent', 'page_size', 'page_token', ), - 'lookup_entry': ('linked_resource', 'sql_resource', ), - 'rename_tag_template_field': ('name', 'new_tag_template_field_id', ), - 'search_catalog': ('scope', 'query', 'page_size', 'page_token', 'order_by', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_entry': ('entry', 'update_mask', ), - 'update_entry_group': ('entry_group', 'update_mask', ), - 'update_policy_tag': ('policy_tag', 'update_mask', ), - 'update_tag': ('tag', 'update_mask', ), - 'update_tag_template': ('tag_template', 'update_mask', ), - 'update_tag_template_field': ('name', 'tag_template_field', 'update_mask', ), - 'update_taxonomy': ('taxonomy', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=datacatalogCallTransformer(), -): - """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 datacatalog 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py deleted file mode 100644 index f76df593..00000000 --- a/owl-bot-staging/v1beta1/setup.py +++ /dev/null @@ -1,55 +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-datacatalog', - 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.28.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.19.4', - 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', - ), - 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/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/__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/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py deleted file mode 100644 index 50ad3e77..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py +++ /dev/null @@ -1,8035 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1beta1.services.data_catalog import DataCatalogAsyncClient -from google.cloud.datacatalog_v1beta1.services.data_catalog import DataCatalogClient -from google.cloud.datacatalog_v1beta1.services.data_catalog import pagers -from google.cloud.datacatalog_v1beta1.services.data_catalog import transports -from google.cloud.datacatalog_v1beta1.types import common -from google.cloud.datacatalog_v1beta1.types import datacatalog -from google.cloud.datacatalog_v1beta1.types import gcs_fileset_spec -from google.cloud.datacatalog_v1beta1.types import schema -from google.cloud.datacatalog_v1beta1.types import search -from google.cloud.datacatalog_v1beta1.types import table_spec -from google.cloud.datacatalog_v1beta1.types import tags -from google.cloud.datacatalog_v1beta1.types import timestamps -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DataCatalogClient._get_default_mtls_endpoint(None) is None - assert DataCatalogClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataCatalogClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DataCatalogClient, - DataCatalogAsyncClient, -]) -def test_data_catalog_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DataCatalogGrpcTransport, "grpc"), - (transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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", [ - DataCatalogClient, - DataCatalogAsyncClient, -]) -def test_data_catalog_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 == 'datacatalog.googleapis.com:443' - - -def test_data_catalog_client_get_transport_class(): - transport = DataCatalogClient.get_transport_class() - available_transports = [ - transports.DataCatalogGrpcTransport, - ] - assert transport in available_transports - - transport = DataCatalogClient.get_transport_class("grpc") - assert transport == transports.DataCatalogGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) -@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) -def test_data_catalog_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(DataCatalogClient, '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(DataCatalogClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "true"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc", "false"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DataCatalogClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogClient)) -@mock.patch.object(DataCatalogAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataCatalogAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_catalog_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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(transport=transport_name, 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", [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - (DataCatalogAsyncClient, transports.DataCatalogGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_data_catalog_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(transport=transport_name, 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_catalog_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DataCatalogClient( - 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_search_catalog(transport: str = 'grpc', request_type=datacatalog.SearchCatalogRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse( - next_page_token='next_page_token_value', - ) - response = client.search_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchCatalogPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_catalog_from_dict(): - test_search_catalog(request_type=dict) - - -def test_search_catalog_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 = DataCatalogClient( - 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.search_catalog), - '__call__') as call: - client.search_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - -@pytest.mark.asyncio -async def test_search_catalog_async(transport: str = 'grpc_asyncio', request_type=datacatalog.SearchCatalogRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.SearchCatalogRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchCatalogAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_catalog_async_from_dict(): - await test_search_catalog_async(request_type=dict) - - -def test_search_catalog_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_catalog( - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) - assert args[0].query == 'query_value' - - -def test_search_catalog_flattened_error(): - client = DataCatalogClient( - 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.search_catalog( - datacatalog.SearchCatalogRequest(), - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_value', - ) - - -@pytest.mark.asyncio -async def test_search_catalog_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.SearchCatalogResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.SearchCatalogResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_catalog( - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_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].scope == datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']) - assert args[0].query == 'query_value' - - -@pytest.mark.asyncio -async def test_search_catalog_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.search_catalog( - datacatalog.SearchCatalogRequest(), - scope=datacatalog.SearchCatalogRequest.Scope(include_org_ids=['include_org_ids_value']), - query='query_value', - ) - - -def test_search_catalog_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.search_catalog(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, search.SearchCatalogResult) - for i in results) - -def test_search_catalog_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search_catalog(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_search_catalog_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_catalog(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, search.SearchCatalogResult) - for i in responses) - -@pytest.mark.asyncio -async def test_search_catalog_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_catalog), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - next_page_token='abc', - ), - datacatalog.SearchCatalogResponse( - results=[], - next_page_token='def', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - ], - next_page_token='ghi', - ), - datacatalog.SearchCatalogResponse( - results=[ - search.SearchCatalogResult(), - search.SearchCatalogResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_catalog(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_entry_group(transport: str = 'grpc', request_type=datacatalog.CreateEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_entry_group_from_dict(): - test_create_entry_group(request_type=dict) - - -def test_create_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.create_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_create_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_entry_group_async_from_dict(): - await test_create_entry_group_async(request_type=dict) - - -def test_create_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.create_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.create_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entry_group( - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' - assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') - - -def test_create_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.CreateEntryGroupRequest(), - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entry_group( - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(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].entry_group_id == 'entry_group_id_value' - assert args[0].entry_group == datacatalog.EntryGroup(name='name_value') - - -@pytest.mark.asyncio -async def test_create_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.CreateEntryGroupRequest(), - parent='parent_value', - entry_group_id='entry_group_id_value', - entry_group=datacatalog.EntryGroup(name='name_value'), - ) - - -def test_update_entry_group(transport: str = 'grpc', request_type=datacatalog.UpdateEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_entry_group_from_dict(): - test_update_entry_group(request_type=dict) - - -def test_update_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.update_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_update_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_entry_group_async_from_dict(): - await test_update_entry_group_async(request_type=dict) - - -def test_update_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryGroupRequest() - - request.entry_group.name = 'entry_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.update_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'entry_group.name=entry_group.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryGroupRequest() - - request.entry_group.name = 'entry_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.update_entry_group(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', - 'entry_group.name=entry_group.name/value', - ) in kw['metadata'] - - -def test_update_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entry_group( - entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.UpdateEntryGroupRequest(), - entry_group=datacatalog.EntryGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entry_group( - entry_group=datacatalog.EntryGroup(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].entry_group == datacatalog.EntryGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.UpdateEntryGroupRequest(), - entry_group=datacatalog.EntryGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_entry_group(transport: str = 'grpc', request_type=datacatalog.GetEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_entry_group_from_dict(): - test_get_entry_group(request_type=dict) - - -def test_get_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.get_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_get_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.EntryGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_entry_group_async_from_dict(): - await test_get_entry_group_async(request_type=dict) - - -def test_get_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - call.return_value = datacatalog.EntryGroup() - client.get_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - await client.get_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entry_group( - name='name_value', - read_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].name == 'name_value' - assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_get_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.GetEntryGroupRequest(), - name='name_value', - read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_get_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.EntryGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.EntryGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entry_group( - name='name_value', - read_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].name == 'name_value' - assert args[0].read_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_get_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.GetEntryGroupRequest(), - name='name_value', - read_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_entry_group(transport: str = 'grpc', request_type=datacatalog.DeleteEntryGroupRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entry_group_from_dict(): - test_delete_entry_group(request_type=dict) - - -def test_delete_entry_group_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 = DataCatalogClient( - 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_entry_group), - '__call__') as call: - client.delete_entry_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - -@pytest.mark.asyncio -async def test_delete_entry_group_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryGroupRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entry_group_async_from_dict(): - await test_delete_entry_group_async(request_type=dict) - - -def test_delete_entry_group_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__call__') as call: - call.return_value = None - client.delete_entry_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_group_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entry_group(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_entry_group_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__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_entry_group( - 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_entry_group_flattened_error(): - client = DataCatalogClient( - 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_entry_group( - datacatalog.DeleteEntryGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_entry_group_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry_group), - '__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_entry_group( - 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_entry_group_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_group( - datacatalog.DeleteEntryGroupRequest(), - name='name_value', - ) - - -def test_list_entry_groups(transport: str = 'grpc', request_type=datacatalog.ListEntryGroupsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntryGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entry_groups_from_dict(): - test_list_entry_groups(request_type=dict) - - -def test_list_entry_groups_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 = DataCatalogClient( - 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_entry_groups), - '__call__') as call: - client.list_entry_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - -@pytest.mark.asyncio -async def test_list_entry_groups_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntryGroupsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntryGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntryGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_entry_groups_async_from_dict(): - await test_list_entry_groups_async(request_type=dict) - - -def test_list_entry_groups_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntryGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - call.return_value = datacatalog.ListEntryGroupsResponse() - client.list_entry_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_groups_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntryGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) - await client.list_entry_groups(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_entry_groups_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entry_groups( - 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_entry_groups_flattened_error(): - client = DataCatalogClient( - 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_entry_groups( - datacatalog.ListEntryGroupsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_entry_groups_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntryGroupsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntryGroupsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entry_groups( - 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_entry_groups_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry_groups( - datacatalog.ListEntryGroupsRequest(), - parent='parent_value', - ) - - -def test_list_entry_groups_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entry_groups(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, datacatalog.EntryGroup) - for i in results) - -def test_list_entry_groups_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entry_groups(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_entry_groups_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entry_groups(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, datacatalog.EntryGroup) - for i in responses) - -@pytest.mark.asyncio -async def test_list_entry_groups_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entry_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - next_page_token='abc', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[], - next_page_token='def', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntryGroupsResponse( - entry_groups=[ - datacatalog.EntryGroup(), - datacatalog.EntryGroup(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entry_groups(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_entry(transport: str = 'grpc', request_type=datacatalog.CreateEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - ) - response = client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_entry_from_dict(): - test_create_entry(request_type=dict) - - -def test_create_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.create_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - -@pytest.mark.asyncio -async def test_create_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_entry_async_from_dict(): - await test_create_entry_async(request_type=dict) - - -def test_create_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.create_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateEntryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.create_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entry( - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(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].entry_id == 'entry_id_value' - assert args[0].entry == datacatalog.Entry(name='name_value') - - -def test_create_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.CreateEntryRequest(), - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entry( - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(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].entry_id == 'entry_id_value' - assert args[0].entry == datacatalog.Entry(name='name_value') - - -@pytest.mark.asyncio -async def test_create_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.CreateEntryRequest(), - parent='parent_value', - entry_id='entry_id_value', - entry=datacatalog.Entry(name='name_value'), - ) - - -def test_update_entry(transport: str = 'grpc', request_type=datacatalog.UpdateEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - ) - response = client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_entry_from_dict(): - test_update_entry(request_type=dict) - - -def test_update_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.update_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - -@pytest.mark.asyncio -async def test_update_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_entry_async_from_dict(): - await test_update_entry_async(request_type=dict) - - -def test_update_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryRequest() - - request.entry.name = 'entry.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.update_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'entry.name=entry.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateEntryRequest() - - request.entry.name = 'entry.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.update_entry(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', - 'entry.name=entry.name/value', - ) in kw['metadata'] - - -def test_update_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entry( - entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.UpdateEntryRequest(), - entry=datacatalog.Entry(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entry( - entry=datacatalog.Entry(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].entry == datacatalog.Entry(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.UpdateEntryRequest(), - entry=datacatalog.Entry(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_entry(transport: str = 'grpc', request_type=datacatalog.DeleteEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entry_from_dict(): - test_delete_entry(request_type=dict) - - -def test_delete_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.delete_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - -@pytest.mark.asyncio -async def test_delete_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteEntryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entry_async_from_dict(): - await test_delete_entry_async(request_type=dict) - - -def test_delete_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__call__') as call: - call.return_value = None - client.delete_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__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_entry( - 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_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.DeleteEntryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entry), - '__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_entry( - 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_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.DeleteEntryRequest(), - name='name_value', - ) - - -def test_get_entry(transport: str = 'grpc', request_type=datacatalog.GetEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - ) - response = client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_entry_from_dict(): - test_get_entry(request_type=dict) - - -def test_get_entry_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 = DataCatalogClient( - 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_entry), - '__call__') as call: - client.get_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - -@pytest.mark.asyncio -async def test_get_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_entry_async_from_dict(): - await test_get_entry_async(request_type=dict) - - -def test_get_entry_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - call.return_value = datacatalog.Entry() - client.get_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_entry_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetEntryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - await client.get_entry(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_entry_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entry( - 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_entry_flattened_error(): - client = DataCatalogClient( - 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_entry( - datacatalog.GetEntryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_entry_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entry( - 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_entry_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entry( - datacatalog.GetEntryRequest(), - name='name_value', - ) - - -def test_lookup_entry(transport: str = 'grpc', request_type=datacatalog.LookupEntryRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - type_=datacatalog.EntryType.TABLE, - integrated_system=common.IntegratedSystem.BIGQUERY, - gcs_fileset_spec=gcs_fileset_spec.GcsFilesetSpec(file_patterns=['file_patterns_value']), - ) - response = client.lookup_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_lookup_entry_from_dict(): - test_lookup_entry(request_type=dict) - - -def test_lookup_entry_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 = DataCatalogClient( - 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.lookup_entry), - '__call__') as call: - client.lookup_entry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - -@pytest.mark.asyncio -async def test_lookup_entry_async(transport: str = 'grpc_asyncio', request_type=datacatalog.LookupEntryRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_entry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.Entry( - name='name_value', - linked_resource='linked_resource_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.lookup_entry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.LookupEntryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, datacatalog.Entry) - assert response.name == 'name_value' - assert response.linked_resource == 'linked_resource_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_lookup_entry_async_from_dict(): - await test_lookup_entry_async(request_type=dict) - - -def test_list_entries(transport: str = 'grpc', request_type=datacatalog.ListEntriesRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entries_from_dict(): - test_list_entries(request_type=dict) - - -def test_list_entries_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 = DataCatalogClient( - 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_entries), - '__call__') as call: - client.list_entries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - -@pytest.mark.asyncio -async def test_list_entries_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListEntriesRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_entries_async_from_dict(): - await test_list_entries_async(request_type=dict) - - -def test_list_entries_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - call.return_value = datacatalog.ListEntriesResponse() - client.list_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_entries_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListEntriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) - await client.list_entries(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_entries_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entries( - 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_entries_flattened_error(): - client = DataCatalogClient( - 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_entries( - datacatalog.ListEntriesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_entries_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListEntriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListEntriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entries( - 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_entries_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_entries( - datacatalog.ListEntriesRequest(), - parent='parent_value', - ) - - -def test_list_entries_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entries(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, datacatalog.Entry) - for i in results) - -def test_list_entries_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entries(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_entries_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entries(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, datacatalog.Entry) - for i in responses) - -@pytest.mark.asyncio -async def test_list_entries_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - datacatalog.Entry(), - ], - next_page_token='abc', - ), - datacatalog.ListEntriesResponse( - entries=[], - next_page_token='def', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - ], - next_page_token='ghi', - ), - datacatalog.ListEntriesResponse( - entries=[ - datacatalog.Entry(), - datacatalog.Entry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entries(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_tag_template(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - ) - response = client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_tag_template_from_dict(): - test_create_tag_template(request_type=dict) - - -def test_create_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.create_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_create_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - )) - response = await client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_create_tag_template_async_from_dict(): - await test_create_tag_template_async(request_type=dict) - - -def test_create_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.create_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.create_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag_template( - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' - assert args[0].tag_template == tags.TagTemplate(name='name_value') - - -def test_create_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.CreateTagTemplateRequest(), - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag_template( - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(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].tag_template_id == 'tag_template_id_value' - assert args[0].tag_template == tags.TagTemplate(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.CreateTagTemplateRequest(), - parent='parent_value', - tag_template_id='tag_template_id_value', - tag_template=tags.TagTemplate(name='name_value'), - ) - - -def test_get_tag_template(transport: str = 'grpc', request_type=datacatalog.GetTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - ) - response = client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_tag_template_from_dict(): - test_get_tag_template(request_type=dict) - - -def test_get_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.get_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_get_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.GetTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.GetTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_tag_template_async_from_dict(): - await test_get_tag_template_async(request_type=dict) - - -def test_get_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.get_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.GetTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.get_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tag_template( - 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_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.GetTagTemplateRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tag_template( - 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_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.GetTagTemplateRequest(), - name='name_value', - ) - - -def test_update_tag_template(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate( - name='name_value', - display_name='display_name_value', - ) - response = client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_tag_template_from_dict(): - test_update_tag_template(request_type=dict) - - -def test_update_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.update_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_update_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplate) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_tag_template_async_from_dict(): - await test_update_tag_template_async(request_type=dict) - - -def test_update_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateRequest() - - request.tag_template.name = 'tag_template.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - call.return_value = tags.TagTemplate() - client.update_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag_template.name=tag_template.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateRequest() - - request.tag_template.name = 'tag_template.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - await client.update_tag_template(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', - 'tag_template.name=tag_template.name/value', - ) in kw['metadata'] - - -def test_update_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_template( - tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.UpdateTagTemplateRequest(), - tag_template=tags.TagTemplate(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplate() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplate()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_template( - tag_template=tags.TagTemplate(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].tag_template == tags.TagTemplate(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.UpdateTagTemplateRequest(), - tag_template=tags.TagTemplate(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_tag_template(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_template_from_dict(): - test_delete_tag_template(request_type=dict) - - -def test_delete_tag_template_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 = DataCatalogClient( - 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_tag_template), - '__call__') as call: - client.delete_tag_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_template_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_template_async_from_dict(): - await test_delete_tag_template_async(request_type=dict) - - -def test_delete_tag_template_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__call__') as call: - call.return_value = None - client.delete_tag_template(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag_template(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_tag_template_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__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_tag_template( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -def test_delete_tag_template_flattened_error(): - client = DataCatalogClient( - 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_tag_template( - datacatalog.DeleteTagTemplateRequest(), - name='name_value', - force=True, - ) - - -@pytest.mark.asyncio -async def test_delete_tag_template_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template), - '__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_tag_template( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -@pytest.mark.asyncio -async def test_delete_tag_template_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template( - datacatalog.DeleteTagTemplateRequest(), - name='name_value', - force=True, - ) - - -def test_create_tag_template_field(transport: str = 'grpc', request_type=datacatalog.CreateTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - ) - response = client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -def test_create_tag_template_field_from_dict(): - test_create_tag_template_field(request_type=dict) - - -def test_create_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.create_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_create_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - )) - response = await client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_create_tag_template_field_async_from_dict(): - await test_create_tag_template_field_async(request_type=dict) - - -def test_create_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateFieldRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.create_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagTemplateFieldRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.create_tag_template_field(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_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag_template_field( - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - - -def test_create_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.CreateTagTemplateFieldRequest(), - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag_template_field( - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(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].tag_template_field_id == 'tag_template_field_id_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.CreateTagTemplateFieldRequest(), - parent='parent_value', - tag_template_field_id='tag_template_field_id_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - ) - - -def test_update_tag_template_field(transport: str = 'grpc', request_type=datacatalog.UpdateTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - ) - response = client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -def test_update_tag_template_field_from_dict(): - test_update_tag_template_field(request_type=dict) - - -def test_update_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.update_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_update_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - )) - response = await client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_update_tag_template_field_async_from_dict(): - await test_update_tag_template_field_async(request_type=dict) - - -def test_update_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.update_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_update_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.update_tag_template_field(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_update_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_template_field( - name='name_value', - tag_template_field=tags.TagTemplateField(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].name == 'name_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.UpdateTagTemplateFieldRequest(), - name='name_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_template_field( - name='name_value', - tag_template_field=tags.TagTemplateField(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].name == 'name_value' - assert args[0].tag_template_field == tags.TagTemplateField(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.UpdateTagTemplateFieldRequest(), - name='name_value', - tag_template_field=tags.TagTemplateField(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_rename_tag_template_field(transport: str = 'grpc', request_type=datacatalog.RenameTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - ) - response = client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -def test_rename_tag_template_field_from_dict(): - test_rename_tag_template_field(request_type=dict) - - -def test_rename_tag_template_field_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 = DataCatalogClient( - 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.rename_tag_template_field), - '__call__') as call: - client.rename_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.RenameTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField( - name='name_value', - display_name='display_name_value', - is_required=True, - order=540, - )) - response = await client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.RenameTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.TagTemplateField) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.is_required is True - assert response.order == 540 - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_async_from_dict(): - await test_rename_tag_template_field_async(request_type=dict) - - -def test_rename_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - call.return_value = tags.TagTemplateField() - client.rename_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_rename_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.RenameTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - await client.rename_tag_template_field(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_rename_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.rename_tag_template_field( - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' - - -def test_rename_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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.rename_tag_template_field( - datacatalog.RenameTagTemplateFieldRequest(), - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rename_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.TagTemplateField() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.TagTemplateField()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.rename_tag_template_field( - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].new_tag_template_field_id == 'new_tag_template_field_id_value' - - -@pytest.mark.asyncio -async def test_rename_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.rename_tag_template_field( - datacatalog.RenameTagTemplateFieldRequest(), - name='name_value', - new_tag_template_field_id='new_tag_template_field_id_value', - ) - - -def test_delete_tag_template_field(transport: str = 'grpc', request_type=datacatalog.DeleteTagTemplateFieldRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_template_field_from_dict(): - test_delete_tag_template_field(request_type=dict) - - -def test_delete_tag_template_field_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 = DataCatalogClient( - 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_tag_template_field), - '__call__') as call: - client.delete_tag_template_field() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagTemplateFieldRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_template_field), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagTemplateFieldRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_async_from_dict(): - await test_delete_tag_template_field_async(request_type=dict) - - -def test_delete_tag_template_field_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__call__') as call: - call.return_value = None - client.delete_tag_template_field(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_template_field_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagTemplateFieldRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag_template_field(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_tag_template_field_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__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_tag_template_field( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -def test_delete_tag_template_field_flattened_error(): - client = DataCatalogClient( - 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_tag_template_field( - datacatalog.DeleteTagTemplateFieldRequest(), - name='name_value', - force=True, - ) - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_template_field), - '__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_tag_template_field( - name='name_value', - force=True, - ) - - # 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' - assert args[0].force == True - - -@pytest.mark.asyncio -async def test_delete_tag_template_field_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag_template_field( - datacatalog.DeleteTagTemplateFieldRequest(), - name='name_value', - force=True, - ) - - -def test_create_tag(transport: str = 'grpc', request_type=datacatalog.CreateTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - column='column_value', - ) - response = client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -def test_create_tag_from_dict(): - test_create_tag(request_type=dict) - - -def test_create_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.create_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - -@pytest.mark.asyncio -async def test_create_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.CreateTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - )) - response = await client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.CreateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -@pytest.mark.asyncio -async def test_create_tag_async_from_dict(): - await test_create_tag_async(request_type=dict) - - -def test_create_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - call.return_value = tags.Tag() - client.create_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.CreateTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - await client.create_tag(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_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_tag( - parent='parent_value', - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - - -def test_create_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.CreateTagRequest(), - parent='parent_value', - tag=tags.Tag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_tag( - parent='parent_value', - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - - -@pytest.mark.asyncio -async def test_create_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.CreateTagRequest(), - parent='parent_value', - tag=tags.Tag(name='name_value'), - ) - - -def test_update_tag(transport: str = 'grpc', request_type=datacatalog.UpdateTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - column='column_value', - ) - response = client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -def test_update_tag_from_dict(): - test_update_tag(request_type=dict) - - -def test_update_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.update_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - -@pytest.mark.asyncio -async def test_update_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.UpdateTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag( - name='name_value', - template='template_value', - template_display_name='template_display_name_value', - )) - response = await client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.UpdateTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tags.Tag) - assert response.name == 'name_value' - assert response.template == 'template_value' - assert response.template_display_name == 'template_display_name_value' - - -@pytest.mark.asyncio -async def test_update_tag_async_from_dict(): - await test_update_tag_async(request_type=dict) - - -def test_update_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagRequest() - - request.tag.name = 'tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - call.return_value = tags.Tag() - client.update_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag.name=tag.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.UpdateTagRequest() - - request.tag.name = 'tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - await client.update_tag(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', - 'tag.name=tag.name/value', - ) in kw['metadata'] - - -def test_update_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag( - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.UpdateTagRequest(), - tag=tags.Tag(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tags.Tag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tags.Tag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag( - tag=tags.Tag(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].tag == tags.Tag(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.UpdateTagRequest(), - tag=tags.Tag(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_tag(transport: str = 'grpc', request_type=datacatalog.DeleteTagRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_tag_from_dict(): - test_delete_tag(request_type=dict) - - -def test_delete_tag_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 = DataCatalogClient( - 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_tag), - '__call__') as call: - client.delete_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - -@pytest.mark.asyncio -async def test_delete_tag_async(transport: str = 'grpc_asyncio', request_type=datacatalog.DeleteTagRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.DeleteTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_tag_async_from_dict(): - await test_delete_tag_async(request_type=dict) - - -def test_delete_tag_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__call__') as call: - call.return_value = None - client.delete_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_tag_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.DeleteTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_tag(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_tag_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__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_tag( - 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_tag_flattened_error(): - client = DataCatalogClient( - 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_tag( - datacatalog.DeleteTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_tag_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag), - '__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_tag( - 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_tag_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tag( - datacatalog.DeleteTagRequest(), - name='name_value', - ) - - -def test_list_tags(transport: str = 'grpc', request_type=datacatalog.ListTagsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tags_from_dict(): - test_list_tags(request_type=dict) - - -def test_list_tags_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 = DataCatalogClient( - 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_tags), - '__call__') as call: - client.list_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - -@pytest.mark.asyncio -async def test_list_tags_async(transport: str = 'grpc_asyncio', request_type=datacatalog.ListTagsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == datacatalog.ListTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tags_async_from_dict(): - await test_list_tags_async(request_type=dict) - - -def test_list_tags_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - call.return_value = datacatalog.ListTagsResponse() - client.list_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_tags_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = datacatalog.ListTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) - await client.list_tags(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_tags_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tags( - 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_tags_flattened_error(): - client = DataCatalogClient( - 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_tags( - datacatalog.ListTagsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_tags_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = datacatalog.ListTagsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(datacatalog.ListTagsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tags( - 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_tags_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_tags( - datacatalog.ListTagsRequest(), - parent='parent_value', - ) - - -def test_list_tags_pager(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_tags(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, tags.Tag) - for i in results) - -def test_list_tags_pages(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tags(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_tags_async_pager(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tags(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, tags.Tag) - for i in responses) - -@pytest.mark.asyncio -async def test_list_tags_async_pages(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - tags.Tag(), - ], - next_page_token='abc', - ), - datacatalog.ListTagsResponse( - tags=[], - next_page_token='def', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - ], - next_page_token='ghi', - ), - datacatalog.ListTagsResponse( - tags=[ - tags.Tag(), - tags.Tag(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_tags(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataCatalogClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_set_iam_policy_async_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_set_iam_policy_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy(request={ - 'resource': 'resource_value', - 'policy': policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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].resource == 'resource_value' - - -def test_set_iam_policy_flattened_error(): - client = DataCatalogClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_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].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = DataCatalogAsyncClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DataCatalogClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_get_iam_policy_async_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_get_iam_policy_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_get_iam_policy_flattened(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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].resource == 'resource_value' - - -def test_get_iam_policy_flattened_error(): - client = DataCatalogClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_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].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = DataCatalogAsyncClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = DataCatalogClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - )) - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_test_iam_permissions_from_dict_foreign(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions(request={ - 'resource': 'resource_value', - 'permissions': ['permissions_value'], - } - ) - call.assert_called() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DataCatalogClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DataCatalogClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DataCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DataCatalogGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DataCatalogGrpcTransport, - transports.DataCatalogGrpcAsyncIOTransport, -]) -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 = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DataCatalogGrpcTransport, - ) - -def test_data_catalog_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DataCatalogTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_data_catalog_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DataCatalogTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search_catalog', - 'create_entry_group', - 'update_entry_group', - 'get_entry_group', - 'delete_entry_group', - 'list_entry_groups', - 'create_entry', - 'update_entry', - 'delete_entry', - 'get_entry', - 'lookup_entry', - 'list_entries', - 'create_tag_template', - 'get_tag_template', - 'update_tag_template', - 'delete_tag_template', - 'create_tag_template_field', - 'update_tag_template_field', - 'rename_tag_template_field', - 'delete_tag_template_field', - 'create_tag', - 'update_tag', - 'delete_tag', - 'list_tags', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_data_catalog_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.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataCatalogTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_data_catalog_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.datacatalog_v1beta1.services.data_catalog.transports.DataCatalogTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DataCatalogTransport() - adc.assert_called_once() - - -def test_data_catalog_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) - DataCatalogClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DataCatalogGrpcTransport, - transports.DataCatalogGrpcAsyncIOTransport, - ], -) -def test_data_catalog_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,grpc_helpers", - [ - (transports.DataCatalogGrpcTransport, grpc_helpers), - (transports.DataCatalogGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_data_catalog_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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_catalog_host_no_port(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_data_catalog_host_with_port(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_data_catalog_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataCatalogGrpcTransport( - 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_catalog_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DataCatalogGrpcAsyncIOTransport( - 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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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.DataCatalogGrpcTransport, transports.DataCatalogGrpcAsyncIOTransport]) -def test_data_catalog_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_entry_path(): - project = "squid" - location = "clam" - entry_group = "whelk" - entry = "octopus" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format(project=project, location=location, entry_group=entry_group, entry=entry, ) - actual = DataCatalogClient.entry_path(project, location, entry_group, entry) - assert expected == actual - - -def test_parse_entry_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "entry_group": "cuttlefish", - "entry": "mussel", - } - path = DataCatalogClient.entry_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_entry_path(path) - assert expected == actual - -def test_entry_group_path(): - project = "winkle" - location = "nautilus" - entry_group = "scallop" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}".format(project=project, location=location, entry_group=entry_group, ) - actual = DataCatalogClient.entry_group_path(project, location, entry_group) - assert expected == actual - - -def test_parse_entry_group_path(): - expected = { - "project": "abalone", - "location": "squid", - "entry_group": "clam", - } - path = DataCatalogClient.entry_group_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_entry_group_path(path) - assert expected == actual - -def test_tag_path(): - project = "whelk" - location = "octopus" - entry_group = "oyster" - entry = "nudibranch" - tag = "cuttlefish" - expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}".format(project=project, location=location, entry_group=entry_group, entry=entry, tag=tag, ) - actual = DataCatalogClient.tag_path(project, location, entry_group, entry, tag) - assert expected == actual - - -def test_parse_tag_path(): - expected = { - "project": "mussel", - "location": "winkle", - "entry_group": "nautilus", - "entry": "scallop", - "tag": "abalone", - } - path = DataCatalogClient.tag_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_path(path) - assert expected == actual - -def test_tag_template_path(): - project = "squid" - location = "clam" - tag_template = "whelk" - expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}".format(project=project, location=location, tag_template=tag_template, ) - actual = DataCatalogClient.tag_template_path(project, location, tag_template) - assert expected == actual - - -def test_parse_tag_template_path(): - expected = { - "project": "octopus", - "location": "oyster", - "tag_template": "nudibranch", - } - path = DataCatalogClient.tag_template_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_template_path(path) - assert expected == actual - -def test_tag_template_field_path(): - project = "cuttlefish" - location = "mussel" - tag_template = "winkle" - field = "nautilus" - expected = "projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}".format(project=project, location=location, tag_template=tag_template, field=field, ) - actual = DataCatalogClient.tag_template_field_path(project, location, tag_template, field) - assert expected == actual - - -def test_parse_tag_template_field_path(): - expected = { - "project": "scallop", - "location": "abalone", - "tag_template": "squid", - "field": "clam", - } - path = DataCatalogClient.tag_template_field_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_tag_template_field_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DataCatalogClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = DataCatalogClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = DataCatalogClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = DataCatalogClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DataCatalogClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = DataCatalogClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = DataCatalogClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = DataCatalogClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.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 = DataCatalogClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = DataCatalogClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DataCatalogClient.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.DataCatalogTransport, '_prep_wrapped_messages') as prep: - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DataCatalogTransport, '_prep_wrapped_messages') as prep: - transport_class = DataCatalogClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DataCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = DataCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py deleted file mode 100644 index 464a5814..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py +++ /dev/null @@ -1,4233 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import PolicyTagManagerAsyncClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import PolicyTagManagerClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import pagers -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager import transports -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PolicyTagManagerClient._get_default_mtls_endpoint(None) is None - assert PolicyTagManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PolicyTagManagerClient, - PolicyTagManagerAsyncClient, -]) -def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PolicyTagManagerGrpcTransport, "grpc"), - (transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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", [ - PolicyTagManagerClient, - PolicyTagManagerAsyncClient, -]) -def test_policy_tag_manager_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 == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_client_get_transport_class(): - transport = PolicyTagManagerClient.get_transport_class() - available_transports = [ - transports.PolicyTagManagerGrpcTransport, - ] - assert transport in available_transports - - transport = PolicyTagManagerClient.get_transport_class("grpc") - assert transport == transports.PolicyTagManagerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) -@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) -def test_policy_tag_manager_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(PolicyTagManagerClient, '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(PolicyTagManagerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "true"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc", "false"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PolicyTagManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerClient)) -@mock.patch.object(PolicyTagManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_policy_tag_manager_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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(transport=transport_name, 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", [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - (PolicyTagManagerAsyncClient, transports.PolicyTagManagerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_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(transport=transport_name, 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_policy_tag_manager_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PolicyTagManagerClient( - 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_create_taxonomy(transport: str = 'grpc', request_type=policytagmanager.CreateTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_create_taxonomy_from_dict(): - test_create_taxonomy(request_type=dict) - - -def test_create_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.create_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_create_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreateTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_create_taxonomy_async_from_dict(): - await test_create_taxonomy_async(request_type=dict) - - -def test_create_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreateTaxonomyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.create_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreateTaxonomyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.create_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_taxonomy( - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -def test_create_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.CreateTaxonomyRequest(), - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_taxonomy( - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -@pytest.mark.asyncio -async def test_create_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.CreateTaxonomyRequest(), - parent='parent_value', - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -def test_delete_taxonomy(transport: str = 'grpc', request_type=policytagmanager.DeleteTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_taxonomy_from_dict(): - test_delete_taxonomy(request_type=dict) - - -def test_delete_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.delete_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_delete_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeleteTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeleteTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_taxonomy_async_from_dict(): - await test_delete_taxonomy_async(request_type=dict) - - -def test_delete_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeleteTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__call__') as call: - call.return_value = None - client.delete_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeleteTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__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_taxonomy( - 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_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.DeleteTaxonomyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_taxonomy), - '__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_taxonomy( - 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_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.DeleteTaxonomyRequest(), - name='name_value', - ) - - -def test_update_taxonomy(transport: str = 'grpc', request_type=policytagmanager.UpdateTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_update_taxonomy_from_dict(): - test_update_taxonomy(request_type=dict) - - -def test_update_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.update_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_update_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdateTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdateTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_update_taxonomy_async_from_dict(): - await test_update_taxonomy_async(request_type=dict) - - -def test_update_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdateTaxonomyRequest() - - request.taxonomy.name = 'taxonomy.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.update_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'taxonomy.name=taxonomy.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdateTaxonomyRequest() - - request.taxonomy.name = 'taxonomy.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.update_taxonomy(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', - 'taxonomy.name=taxonomy.name/value', - ) in kw['metadata'] - - -def test_update_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_taxonomy( - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -def test_update_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.UpdateTaxonomyRequest(), - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_taxonomy( - taxonomy=policytagmanager.Taxonomy(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].taxonomy == policytagmanager.Taxonomy(name='name_value') - - -@pytest.mark.asyncio -async def test_update_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.UpdateTaxonomyRequest(), - taxonomy=policytagmanager.Taxonomy(name='name_value'), - ) - - -def test_list_taxonomies(transport: str = 'grpc', request_type=policytagmanager.ListTaxonomiesRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTaxonomiesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_taxonomies_from_dict(): - test_list_taxonomies(request_type=dict) - - -def test_list_taxonomies_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 = PolicyTagManagerClient( - 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_taxonomies), - '__call__') as call: - client.list_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_list_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListTaxonomiesRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTaxonomiesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_taxonomies_async_from_dict(): - await test_list_taxonomies_async(request_type=dict) - - -def test_list_taxonomies_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - call.return_value = policytagmanager.ListTaxonomiesResponse() - client.list_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_taxonomies_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) - await client.list_taxonomies(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_taxonomies_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_taxonomies( - 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_taxonomies_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomies( - policytagmanager.ListTaxonomiesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_taxonomies_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListTaxonomiesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListTaxonomiesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_taxonomies( - 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_taxonomies_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomies( - policytagmanager.ListTaxonomiesRequest(), - parent='parent_value', - ) - - -def test_list_taxonomies_pager(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_taxonomies(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, policytagmanager.Taxonomy) - for i in results) - -def test_list_taxonomies_pages(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_taxonomies(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_taxonomies_async_pager(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_taxonomies(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, policytagmanager.Taxonomy) - for i in responses) - -@pytest.mark.asyncio -async def test_list_taxonomies_async_pages(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_taxonomies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - next_page_token='abc', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[], - next_page_token='def', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - ], - next_page_token='ghi', - ), - policytagmanager.ListTaxonomiesResponse( - taxonomies=[ - policytagmanager.Taxonomy(), - policytagmanager.Taxonomy(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_taxonomies(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_taxonomy(transport: str = 'grpc', request_type=policytagmanager.GetTaxonomyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - ) - response = client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -def test_get_taxonomy_from_dict(): - test_get_taxonomy(request_type=dict) - - -def test_get_taxonomy_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 = PolicyTagManagerClient( - 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_taxonomy), - '__call__') as call: - client.get_taxonomy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - -@pytest.mark.asyncio -async def test_get_taxonomy_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetTaxonomyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy( - name='name_value', - display_name='display_name_value', - description='description_value', - activated_policy_types=[policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL], - )) - response = await client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetTaxonomyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.Taxonomy) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.activated_policy_types == [policytagmanager.Taxonomy.PolicyType.FINE_GRAINED_ACCESS_CONTROL] - - -@pytest.mark.asyncio -async def test_get_taxonomy_async_from_dict(): - await test_get_taxonomy_async(request_type=dict) - - -def test_get_taxonomy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - call.return_value = policytagmanager.Taxonomy() - client.get_taxonomy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_taxonomy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetTaxonomyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - await client.get_taxonomy(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_taxonomy_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_taxonomy( - 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_taxonomy_flattened_error(): - client = PolicyTagManagerClient( - 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_taxonomy( - policytagmanager.GetTaxonomyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_taxonomy_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_taxonomy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.Taxonomy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.Taxonomy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_taxonomy( - 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_taxonomy_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_taxonomy( - policytagmanager.GetTaxonomyRequest(), - name='name_value', - ) - - -def test_create_policy_tag(transport: str = 'grpc', request_type=policytagmanager.CreatePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_create_policy_tag_from_dict(): - test_create_policy_tag(request_type=dict) - - -def test_create_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.create_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_create_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.CreatePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.CreatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_create_policy_tag_async_from_dict(): - await test_create_policy_tag_async(request_type=dict) - - -def test_create_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreatePolicyTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.create_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.CreatePolicyTagRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.create_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_policy_tag( - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -def test_create_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.CreatePolicyTagRequest(), - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_policy_tag( - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -@pytest.mark.asyncio -async def test_create_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.CreatePolicyTagRequest(), - parent='parent_value', - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -def test_delete_policy_tag(transport: str = 'grpc', request_type=policytagmanager.DeletePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_policy_tag_from_dict(): - test_delete_policy_tag(request_type=dict) - - -def test_delete_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.delete_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_delete_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.DeletePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.DeletePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_policy_tag_async_from_dict(): - await test_delete_policy_tag_async(request_type=dict) - - -def test_delete_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeletePolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__call__') as call: - call.return_value = None - client.delete_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.DeletePolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__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_policy_tag( - 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_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.DeletePolicyTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_policy_tag), - '__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_policy_tag( - 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_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.DeletePolicyTagRequest(), - name='name_value', - ) - - -def test_update_policy_tag(transport: str = 'grpc', request_type=policytagmanager.UpdatePolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_update_policy_tag_from_dict(): - test_update_policy_tag(request_type=dict) - - -def test_update_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.update_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - -@pytest.mark.asyncio -async def test_update_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.UpdatePolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.UpdatePolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_update_policy_tag_async_from_dict(): - await test_update_policy_tag_async(request_type=dict) - - -def test_update_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdatePolicyTagRequest() - - request.policy_tag.name = 'policy_tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.update_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'policy_tag.name=policy_tag.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.UpdatePolicyTagRequest() - - request.policy_tag.name = 'policy_tag.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.update_policy_tag(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', - 'policy_tag.name=policy_tag.name/value', - ) in kw['metadata'] - - -def test_update_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_policy_tag( - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -def test_update_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.UpdatePolicyTagRequest(), - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_policy_tag( - policy_tag=policytagmanager.PolicyTag(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].policy_tag == policytagmanager.PolicyTag(name='name_value') - - -@pytest.mark.asyncio -async def test_update_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.UpdatePolicyTagRequest(), - policy_tag=policytagmanager.PolicyTag(name='name_value'), - ) - - -def test_list_policy_tags(transport: str = 'grpc', request_type=policytagmanager.ListPolicyTagsRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPolicyTagsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_policy_tags_from_dict(): - test_list_policy_tags(request_type=dict) - - -def test_list_policy_tags_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 = PolicyTagManagerClient( - 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_policy_tags), - '__call__') as call: - client.list_policy_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - -@pytest.mark.asyncio -async def test_list_policy_tags_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.ListPolicyTagsRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.ListPolicyTagsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPolicyTagsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_policy_tags_async_from_dict(): - await test_list_policy_tags_async(request_type=dict) - - -def test_list_policy_tags_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListPolicyTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - call.return_value = policytagmanager.ListPolicyTagsResponse() - client.list_policy_tags(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_policy_tags_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.ListPolicyTagsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) - await client.list_policy_tags(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_policy_tags_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_policy_tags( - 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_policy_tags_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tags( - policytagmanager.ListPolicyTagsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_policy_tags_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.ListPolicyTagsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.ListPolicyTagsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_policy_tags( - 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_policy_tags_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tags( - policytagmanager.ListPolicyTagsRequest(), - parent='parent_value', - ) - - -def test_list_policy_tags_pager(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_policy_tags(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, policytagmanager.PolicyTag) - for i in results) - -def test_list_policy_tags_pages(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - pages = list(client.list_policy_tags(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_policy_tags_async_pager(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_policy_tags(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, policytagmanager.PolicyTag) - for i in responses) - -@pytest.mark.asyncio -async def test_list_policy_tags_async_pages(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_policy_tags), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - next_page_token='abc', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[], - next_page_token='def', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - ], - next_page_token='ghi', - ), - policytagmanager.ListPolicyTagsResponse( - policy_tags=[ - policytagmanager.PolicyTag(), - policytagmanager.PolicyTag(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_policy_tags(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_policy_tag(transport: str = 'grpc', request_type=policytagmanager.GetPolicyTagRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - ) - response = client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -def test_get_policy_tag_from_dict(): - test_get_policy_tag(request_type=dict) - - -def test_get_policy_tag_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 = PolicyTagManagerClient( - 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_policy_tag), - '__call__') as call: - client.get_policy_tag() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - -@pytest.mark.asyncio -async def test_get_policy_tag_async(transport: str = 'grpc_asyncio', request_type=policytagmanager.GetPolicyTagRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag( - name='name_value', - display_name='display_name_value', - description='description_value', - parent_policy_tag='parent_policy_tag_value', - child_policy_tags=['child_policy_tags_value'], - )) - response = await client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanager.GetPolicyTagRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanager.PolicyTag) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.parent_policy_tag == 'parent_policy_tag_value' - assert response.child_policy_tags == ['child_policy_tags_value'] - - -@pytest.mark.asyncio -async def test_get_policy_tag_async_from_dict(): - await test_get_policy_tag_async(request_type=dict) - - -def test_get_policy_tag_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetPolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - call.return_value = policytagmanager.PolicyTag() - client.get_policy_tag(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_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_policy_tag_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanager.GetPolicyTagRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - await client.get_policy_tag(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_policy_tag_flattened(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_policy_tag( - 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_policy_tag_flattened_error(): - client = PolicyTagManagerClient( - 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_policy_tag( - policytagmanager.GetPolicyTagRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_policy_tag_flattened_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_policy_tag), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanager.PolicyTag() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanager.PolicyTag()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_policy_tag( - 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_policy_tag_flattened_error_async(): - client = PolicyTagManagerAsyncClient( - 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_policy_tag( - policytagmanager.GetPolicyTagRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTagManagerClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_get_iam_policy_async_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_get_iam_policy_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTagManagerClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_set_iam_policy_async_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_set_iam_policy_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy(request={ - 'resource': 'resource_value', - 'policy': policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = PolicyTagManagerClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - )) - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'resource=resource/value', - ) in kw['metadata'] - -def test_test_iam_permissions_from_dict_foreign(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions(request={ - 'resource': 'resource_value', - 'permissions': ['permissions_value'], - } - ) - call.assert_called() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PolicyTagManagerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PolicyTagManagerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PolicyTagManagerGrpcTransport, - transports.PolicyTagManagerGrpcAsyncIOTransport, -]) -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 = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PolicyTagManagerGrpcTransport, - ) - -def test_policy_tag_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PolicyTagManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_policy_tag_manager_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PolicyTagManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_taxonomy', - 'delete_taxonomy', - 'update_taxonomy', - 'list_taxonomies', - 'get_taxonomy', - 'create_policy_tag', - 'delete_policy_tag', - 'update_policy_tag', - 'list_policy_tags', - 'get_policy_tag', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_policy_tag_manager_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.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_policy_tag_manager_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.datacatalog_v1beta1.services.policy_tag_manager.transports.PolicyTagManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerTransport() - adc.assert_called_once() - - -def test_policy_tag_manager_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) - PolicyTagManagerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PolicyTagManagerGrpcTransport, - transports.PolicyTagManagerGrpcAsyncIOTransport, - ], -) -def test_policy_tag_manager_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,grpc_helpers", - [ - (transports.PolicyTagManagerGrpcTransport, grpc_helpers), - (transports.PolicyTagManagerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_policy_tag_manager_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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_policy_tag_manager_host_no_port(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_host_with_port(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_policy_tag_manager_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerGrpcTransport( - 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_policy_tag_manager_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerGrpcAsyncIOTransport( - 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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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.PolicyTagManagerGrpcTransport, transports.PolicyTagManagerGrpcAsyncIOTransport]) -def test_policy_tag_manager_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_policy_tag_path(): - project = "squid" - location = "clam" - taxonomy = "whelk" - policy_tag = "octopus" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}/policyTags/{policy_tag}".format(project=project, location=location, taxonomy=taxonomy, policy_tag=policy_tag, ) - actual = PolicyTagManagerClient.policy_tag_path(project, location, taxonomy, policy_tag) - assert expected == actual - - -def test_parse_policy_tag_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "taxonomy": "cuttlefish", - "policy_tag": "mussel", - } - path = PolicyTagManagerClient.policy_tag_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_policy_tag_path(path) - assert expected == actual - -def test_taxonomy_path(): - project = "winkle" - location = "nautilus" - taxonomy = "scallop" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - actual = PolicyTagManagerClient.taxonomy_path(project, location, taxonomy) - assert expected == actual - - -def test_parse_taxonomy_path(): - expected = { - "project": "abalone", - "location": "squid", - "taxonomy": "clam", - } - path = PolicyTagManagerClient.taxonomy_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_taxonomy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PolicyTagManagerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = PolicyTagManagerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = PolicyTagManagerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = PolicyTagManagerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PolicyTagManagerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = PolicyTagManagerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = PolicyTagManagerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = PolicyTagManagerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.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 = PolicyTagManagerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = PolicyTagManagerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerClient.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.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PolicyTagManagerTransport, '_prep_wrapped_messages') as prep: - transport_class = PolicyTagManagerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PolicyTagManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = PolicyTagManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py b/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py deleted file mode 100644 index 0901a0b6..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py +++ /dev/null @@ -1,1210 +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 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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationAsyncClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import PolicyTagManagerSerializationClient -from google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization import transports -from google.cloud.datacatalog_v1beta1.types import policytagmanager -from google.cloud.datacatalog_v1beta1.types import policytagmanagerserialization -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(None) is None - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PolicyTagManagerSerializationClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PolicyTagManagerSerializationClient, - PolicyTagManagerSerializationAsyncClient, -]) -def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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", [ - PolicyTagManagerSerializationClient, - PolicyTagManagerSerializationAsyncClient, -]) -def test_policy_tag_manager_serialization_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 == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_serialization_client_get_transport_class(): - transport = PolicyTagManagerSerializationClient.get_transport_class() - available_transports = [ - transports.PolicyTagManagerSerializationGrpcTransport, - ] - assert transport in available_transports - - transport = PolicyTagManagerSerializationClient.get_transport_class("grpc") - assert transport == transports.PolicyTagManagerSerializationGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) -@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) -def test_policy_tag_manager_serialization_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(PolicyTagManagerSerializationClient, '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(PolicyTagManagerSerializationClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # 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(transport=transport_name, 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", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "true"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc", "false"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PolicyTagManagerSerializationClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationClient)) -@mock.patch.object(PolicyTagManagerSerializationAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PolicyTagManagerSerializationAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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", [ - (PolicyTagManagerSerializationClient, transports.PolicyTagManagerSerializationGrpcTransport, "grpc"), - (PolicyTagManagerSerializationAsyncClient, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_policy_tag_manager_serialization_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(transport=transport_name, 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_policy_tag_manager_serialization_client_client_options_from_dict(): - with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PolicyTagManagerSerializationClient( - 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_import_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse( - ) - response = client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) - - -def test_import_taxonomies_from_dict(): - test_import_taxonomies(request_type=dict) - - -def test_import_taxonomies_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 = PolicyTagManagerSerializationClient( - 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.import_taxonomies), - '__call__') as call: - client.import_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_import_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ImportTaxonomiesRequest): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse( - )) - response = await client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ImportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ImportTaxonomiesResponse) - - -@pytest.mark.asyncio -async def test_import_taxonomies_async_from_dict(): - await test_import_taxonomies_async(request_type=dict) - - -def test_import_taxonomies_field_headers(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ImportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - call.return_value = policytagmanagerserialization.ImportTaxonomiesResponse() - client.import_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_import_taxonomies_field_headers_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ImportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ImportTaxonomiesResponse()) - await client.import_taxonomies(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_export_taxonomies(transport: str = 'grpc', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse( - ) - response = client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) - - -def test_export_taxonomies_from_dict(): - test_export_taxonomies(request_type=dict) - - -def test_export_taxonomies_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 = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - client.export_taxonomies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - -@pytest.mark.asyncio -async def test_export_taxonomies_async(transport: str = 'grpc_asyncio', request_type=policytagmanagerserialization.ExportTaxonomiesRequest): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse( - )) - response = await client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == policytagmanagerserialization.ExportTaxonomiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policytagmanagerserialization.ExportTaxonomiesResponse) - - -@pytest.mark.asyncio -async def test_export_taxonomies_async_from_dict(): - await test_export_taxonomies_async(request_type=dict) - - -def test_export_taxonomies_field_headers(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ExportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - call.return_value = policytagmanagerserialization.ExportTaxonomiesResponse() - client.export_taxonomies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_export_taxonomies_field_headers_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = policytagmanagerserialization.ExportTaxonomiesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_taxonomies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policytagmanagerserialization.ExportTaxonomiesResponse()) - await client.export_taxonomies(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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PolicyTagManagerSerializationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PolicyTagManagerSerializationClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PolicyTagManagerSerializationGrpcTransport, - transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, -]) -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 = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PolicyTagManagerSerializationGrpcTransport, - ) - -def test_policy_tag_manager_serialization_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PolicyTagManagerSerializationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_policy_tag_manager_serialization_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PolicyTagManagerSerializationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'import_taxonomies', - 'export_taxonomies', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -def test_policy_tag_manager_serialization_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.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerSerializationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_policy_tag_manager_serialization_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.datacatalog_v1beta1.services.policy_tag_manager_serialization.transports.PolicyTagManagerSerializationTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PolicyTagManagerSerializationTransport() - adc.assert_called_once() - - -def test_policy_tag_manager_serialization_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) - PolicyTagManagerSerializationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PolicyTagManagerSerializationGrpcTransport, - transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, - ], -) -def test_policy_tag_manager_serialization_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,grpc_helpers", - [ - (transports.PolicyTagManagerSerializationGrpcTransport, grpc_helpers), - (transports.PolicyTagManagerSerializationGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_policy_tag_manager_serialization_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( - "datacatalog.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="datacatalog.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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_policy_tag_manager_serialization_host_no_port(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:443' - - -def test_policy_tag_manager_serialization_host_with_port(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='datacatalog.googleapis.com:8000'), - ) - assert client.transport._host == 'datacatalog.googleapis.com:8000' - -def test_policy_tag_manager_serialization_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerSerializationGrpcTransport( - 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_policy_tag_manager_serialization_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PolicyTagManagerSerializationGrpcAsyncIOTransport( - 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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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.PolicyTagManagerSerializationGrpcTransport, transports.PolicyTagManagerSerializationGrpcAsyncIOTransport]) -def test_policy_tag_manager_serialization_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_taxonomy_path(): - project = "squid" - location = "clam" - taxonomy = "whelk" - expected = "projects/{project}/locations/{location}/taxonomies/{taxonomy}".format(project=project, location=location, taxonomy=taxonomy, ) - actual = PolicyTagManagerSerializationClient.taxonomy_path(project, location, taxonomy) - assert expected == actual - - -def test_parse_taxonomy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "taxonomy": "nudibranch", - } - path = PolicyTagManagerSerializationClient.taxonomy_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_taxonomy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PolicyTagManagerSerializationClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = PolicyTagManagerSerializationClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = PolicyTagManagerSerializationClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = PolicyTagManagerSerializationClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PolicyTagManagerSerializationClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = PolicyTagManagerSerializationClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = PolicyTagManagerSerializationClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = PolicyTagManagerSerializationClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = PolicyTagManagerSerializationClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = PolicyTagManagerSerializationClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PolicyTagManagerSerializationClient.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.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PolicyTagManagerSerializationTransport, '_prep_wrapped_messages') as prep: - transport_class = PolicyTagManagerSerializationClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PolicyTagManagerSerializationAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = PolicyTagManagerSerializationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() From a656cb08b002f1e4a17441596957da7ef2d88b5d Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 5 Nov 2021 09:53:30 +0000 Subject: [PATCH 3/3] add line breaks --- google/cloud/datacatalog_v1/types/bigquery.py | 1 + google/cloud/datacatalog_v1/types/datacatalog.py | 13 +++++++++++++ .../types/policytagmanagerserialization.py | 3 +++ google/cloud/datacatalog_v1/types/search.py | 2 ++ google/cloud/datacatalog_v1/types/table_spec.py | 2 ++ google/cloud/datacatalog_v1/types/tags.py | 9 +++++++++ .../cloud/datacatalog_v1beta1/types/datacatalog.py | 9 +++++++++ .../types/policytagmanagerserialization.py | 1 + .../cloud/datacatalog_v1beta1/types/table_spec.py | 2 ++ google/cloud/datacatalog_v1beta1/types/tags.py | 8 ++++++++ 10 files changed, 50 insertions(+) diff --git a/google/cloud/datacatalog_v1/types/bigquery.py b/google/cloud/datacatalog_v1/types/bigquery.py index db9fef7b..659b3f56 100644 --- a/google/cloud/datacatalog_v1/types/bigquery.py +++ b/google/cloud/datacatalog_v1/types/bigquery.py @@ -37,6 +37,7 @@ class BigQueryConnectionSpec(proto.Message): cloud_sql (google.cloud.datacatalog_v1.types.CloudSqlBigQueryConnectionSpec): Specification for the BigQuery connection to a Cloud SQL instance. + This field is a member of `oneof`_ ``connection_spec``. has_credential (bool): True if there are credentials attached to the diff --git a/google/cloud/datacatalog_v1/types/datacatalog.py b/google/cloud/datacatalog_v1/types/datacatalog.py index 4ba1857b..bab9fa59 100644 --- a/google/cloud/datacatalog_v1/types/datacatalog.py +++ b/google/cloud/datacatalog_v1/types/datacatalog.py @@ -481,6 +481,7 @@ class LookupEntryRequest(proto.Message): - ``//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}`` - ``//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}`` + This field is a member of `oneof`_ ``target_name``. sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. @@ -496,6 +497,7 @@ class LookupEntryRequest(proto.Message): Identifiers (``*_ID``) should comply with the [Lexical structure in Standard SQL] (https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical). + This field is a member of `oneof`_ ``target_name``. fully_qualified_name (str): Fully qualified name (FQN) of the resource. @@ -594,6 +596,7 @@ class Entry(proto.Message): Currently, only ``FILESET`` enum value is allowed. All other entries created in Data Catalog must use the ``user_specified_type``. + This field is a member of `oneof`_ ``entry_type``. user_specified_type (str): Custom entry type that doesn't match any of the values @@ -611,11 +614,13 @@ class Entry(proto.Message): - Can only contain letters, numbers, and underscores. - Must be at least 1 character and at most 64 characters long. + This field is a member of `oneof`_ ``entry_type``. integrated_system (google.cloud.datacatalog_v1.types.IntegratedSystem): Output only. Indicates the entry's source system that Data Catalog integrates with, such as BigQuery, Pub/Sub, or Dataproc Metastore. + This field is a member of `oneof`_ ``system``. user_specified_system (str): Indicates the entry's source system that Data Catalog @@ -629,14 +634,17 @@ class Entry(proto.Message): - Can only contain letters, numbers, and underscores. - Must be at least 1 character and at most 64 characters long. + This field is a member of `oneof`_ ``system``. gcs_fileset_spec (google.cloud.datacatalog_v1.types.GcsFilesetSpec): Specification that applies to a Cloud Storage fileset. Valid only for entries with the ``FILESET`` type. + This field is a member of `oneof`_ ``type_spec``. bigquery_table_spec (google.cloud.datacatalog_v1.types.BigQueryTableSpec): Specification that applies to a BigQuery table. Valid only for entries with the ``TABLE`` type. + This field is a member of `oneof`_ ``type_spec``. bigquery_date_sharded_spec (google.cloud.datacatalog_v1.types.BigQueryDateShardedSpec): Specification for a group of BigQuery tables with the @@ -645,19 +653,23 @@ class Entry(proto.Message): For more information, see [Introduction to partitioned tables] (https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding). + This field is a member of `oneof`_ ``type_spec``. database_table_spec (google.cloud.datacatalog_v1.types.DatabaseTableSpec): Specification that applies to a table resource. Valid only for entries with the ``TABLE`` type. + This field is a member of `oneof`_ ``spec``. data_source_connection_spec (google.cloud.datacatalog_v1.types.DataSourceConnectionSpec): Specification that applies to a data source connection. Valid only for entries with the ``DATA_SOURCE_CONNECTION`` type. + This field is a member of `oneof`_ ``spec``. routine_spec (google.cloud.datacatalog_v1.types.RoutineSpec): Specification that applies to a user-defined function or procedure. Valid only for entries with the ``ROUTINE`` type. + This field is a member of `oneof`_ ``spec``. display_name (str): Display name of an entry. @@ -806,6 +818,7 @@ class RoutineSpec(proto.Message): The body of the routine. bigquery_routine_spec (google.cloud.datacatalog_v1.types.BigQueryRoutineSpec): Fields specific for BigQuery routines. + This field is a member of `oneof`_ ``system_spec``. """ diff --git a/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py b/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py index 9fc96f42..f234e43e 100644 --- a/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py +++ b/google/cloud/datacatalog_v1/types/policytagmanagerserialization.py @@ -129,9 +129,11 @@ class ImportTaxonomiesRequest(proto.Message): imported taxonomies will belong to. inline_source (google.cloud.datacatalog_v1.types.InlineSource): Inline source taxonomy to import. + This field is a member of `oneof`_ ``source``. cross_regional_source (google.cloud.datacatalog_v1.types.CrossRegionalSource): Cross-regional source taxonomy to import. + This field is a member of `oneof`_ ``source``. """ @@ -201,6 +203,7 @@ class ExportTaxonomiesRequest(proto.Message): serialized_taxonomies (bool): Serialized export taxonomies that contain all the policy tags as nested protocol buffers. + This field is a member of `oneof`_ ``destination``. """ diff --git a/google/cloud/datacatalog_v1/types/search.py b/google/cloud/datacatalog_v1/types/search.py index 393e7902..5ce29494 100644 --- a/google/cloud/datacatalog_v1/types/search.py +++ b/google/cloud/datacatalog_v1/types/search.py @@ -82,10 +82,12 @@ class SearchCatalogResult(proto.Message): Output only. The source system that Data Catalog automatically integrates with, such as BigQuery, Cloud Pub/Sub, or Dataproc Metastore. + This field is a member of `oneof`_ ``system``. user_specified_system (str): Custom source system that you can manually integrate Data Catalog with. + This field is a member of `oneof`_ ``system``. fully_qualified_name (str): Fully qualified name (FQN) of the resource. diff --git a/google/cloud/datacatalog_v1/types/table_spec.py b/google/cloud/datacatalog_v1/types/table_spec.py index 83b11fd2..94849b3c 100644 --- a/google/cloud/datacatalog_v1/types/table_spec.py +++ b/google/cloud/datacatalog_v1/types/table_spec.py @@ -52,10 +52,12 @@ class BigQueryTableSpec(proto.Message): view_spec (google.cloud.datacatalog_v1.types.ViewSpec): Table view specification. Populated only if the ``table_source_type`` is ``BIGQUERY_VIEW``. + This field is a member of `oneof`_ ``type_spec``. table_spec (google.cloud.datacatalog_v1.types.TableSpec): Specification of a BigQuery table. Populated only if the ``table_source_type`` is ``BIGQUERY_TABLE``. + This field is a member of `oneof`_ ``type_spec``. """ diff --git a/google/cloud/datacatalog_v1/types/tags.py b/google/cloud/datacatalog_v1/types/tags.py index 912b9744..8b5b34e9 100644 --- a/google/cloud/datacatalog_v1/types/tags.py +++ b/google/cloud/datacatalog_v1/types/tags.py @@ -59,6 +59,7 @@ class Tag(proto.Message): To attach a tag to a nested column, separate column names with a dot (``.``). Example: ``column.nested_column``. + This field is a member of `oneof`_ ``scope``. fields (Sequence[google.cloud.datacatalog_v1.types.Tag.FieldsEntry]): Required. Maps the ID of a tag field to its @@ -92,22 +93,27 @@ class TagField(proto.Message): Output only. The display name of this field. double_value (float): The value of a tag field with a double type. + This field is a member of `oneof`_ ``kind``. string_value (str): The value of a tag field with a string type. The maximum length is 2000 UTF-8 characters. + This field is a member of `oneof`_ ``kind``. bool_value (bool): The value of a tag field with a boolean type. + This field is a member of `oneof`_ ``kind``. timestamp_value (google.protobuf.timestamp_pb2.Timestamp): The value of a tag field with a timestamp type. + This field is a member of `oneof`_ ``kind``. enum_value (google.cloud.datacatalog_v1.types.TagField.EnumValue): The value of a tag field with an enum type. This value must be one of the allowed values listed in this enum. + This field is a member of `oneof`_ ``kind``. richtext_value (str): The value of a tag field with a rich text @@ -116,6 +122,7 @@ class TagField(proto.Message): HTML descriptions including encoded images. The maximum length of the text without images is 100 KiB. + This field is a member of `oneof`_ ``kind``. order (int): Output only. The order of this field with respect to other @@ -297,9 +304,11 @@ class FieldType(proto.Message): primitive_type (google.cloud.datacatalog_v1.types.FieldType.PrimitiveType): Primitive types, such as string, boolean, etc. + This field is a member of `oneof`_ ``type_decl``. enum_type (google.cloud.datacatalog_v1.types.FieldType.EnumType): An enum type. + This field is a member of `oneof`_ ``type_decl``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/datacatalog.py b/google/cloud/datacatalog_v1beta1/types/datacatalog.py index 26da6f59..7d8d7eec 100644 --- a/google/cloud/datacatalog_v1beta1/types/datacatalog.py +++ b/google/cloud/datacatalog_v1beta1/types/datacatalog.py @@ -425,6 +425,7 @@ class LookupEntryRequest(proto.Message): - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId - //pubsub.googleapis.com/projects/projectId/topics/topicId + This field is a member of `oneof`_ ``target_name``. sql_resource (str): The SQL name of the entry. SQL names are case-sensitive. @@ -440,6 +441,7 @@ class LookupEntryRequest(proto.Message): ``*_id``\ s shoud satisfy the standard SQL rules for identifiers. https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. + This field is a member of `oneof`_ ``target_name``. """ @@ -492,6 +494,7 @@ class Entry(proto.Message): The type of the entry. Only used for Entries with types in the EntryType enum. + This field is a member of `oneof`_ ``entry_type``. user_specified_type (str): Entry type if it does not fit any of the input-allowed @@ -507,11 +510,13 @@ class Entry(proto.Message): Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use ``user_specified_type``. + This field is a member of `oneof`_ ``entry_type``. integrated_system (google.cloud.datacatalog_v1beta1.types.IntegratedSystem): Output only. This field indicates the entry's source system that Data Catalog integrates with, such as BigQuery or Pub/Sub. + This field is a member of `oneof`_ ``system``. user_specified_system (str): This field indicates the entry's source system that Data @@ -520,20 +525,24 @@ class Entry(proto.Message): contain letters, numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. + This field is a member of `oneof`_ ``system``. gcs_fileset_spec (google.cloud.datacatalog_v1beta1.types.GcsFilesetSpec): Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. + This field is a member of `oneof`_ ``type_spec``. bigquery_table_spec (google.cloud.datacatalog_v1beta1.types.BigQueryTableSpec): Specification that applies to a BigQuery table. This is only valid on entries of type ``TABLE``. + This field is a member of `oneof`_ ``type_spec``. bigquery_date_sharded_spec (google.cloud.datacatalog_v1beta1.types.BigQueryDateShardedSpec): Specification for a group of BigQuery tables with name pattern ``[prefix]YYYYMMDD``. Context: https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. + This field is a member of `oneof`_ ``type_spec``. display_name (str): Display information such as title and diff --git a/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py b/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py index 87aab667..f8353ee4 100644 --- a/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py +++ b/google/cloud/datacatalog_v1beta1/types/policytagmanagerserialization.py @@ -146,6 +146,7 @@ class ExportTaxonomiesRequest(proto.Message): be exported. serialized_taxonomies (bool): Export taxonomies as serialized taxonomies. + This field is a member of `oneof`_ ``destination``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/table_spec.py b/google/cloud/datacatalog_v1beta1/types/table_spec.py index dd7489fa..005276a4 100644 --- a/google/cloud/datacatalog_v1beta1/types/table_spec.py +++ b/google/cloud/datacatalog_v1beta1/types/table_spec.py @@ -51,10 +51,12 @@ class BigQueryTableSpec(proto.Message): view_spec (google.cloud.datacatalog_v1beta1.types.ViewSpec): Table view specification. This field should only be populated if ``table_source_type`` is ``BIGQUERY_VIEW``. + This field is a member of `oneof`_ ``type_spec``. table_spec (google.cloud.datacatalog_v1beta1.types.TableSpec): Spec of a BigQuery table. This field should only be populated if ``table_source_type`` is ``BIGQUERY_TABLE``. + This field is a member of `oneof`_ ``type_spec``. """ diff --git a/google/cloud/datacatalog_v1beta1/types/tags.py b/google/cloud/datacatalog_v1beta1/types/tags.py index a556873a..3f9d384f 100644 --- a/google/cloud/datacatalog_v1beta1/types/tags.py +++ b/google/cloud/datacatalog_v1beta1/types/tags.py @@ -63,6 +63,7 @@ class Tag(proto.Message): separate the column names. Example: - ``outer_column.inner_column`` + This field is a member of `oneof`_ ``scope``. fields (Sequence[google.cloud.datacatalog_v1beta1.types.Tag.FieldsEntry]): Required. This maps the ID of a tag field to @@ -96,23 +97,28 @@ class TagField(proto.Message): double_value (float): Holds the value for a tag field with double type. + This field is a member of `oneof`_ ``kind``. string_value (str): Holds the value for a tag field with string type. + This field is a member of `oneof`_ ``kind``. bool_value (bool): Holds the value for a tag field with boolean type. + This field is a member of `oneof`_ ``kind``. timestamp_value (google.protobuf.timestamp_pb2.Timestamp): Holds the value for a tag field with timestamp type. + This field is a member of `oneof`_ ``kind``. enum_value (google.cloud.datacatalog_v1beta1.types.TagField.EnumValue): Holds the value for a tag field with enum type. This value must be one of the allowed values in the definition of this enum. + This field is a member of `oneof`_ ``kind``. order (int): Output only. The order of this field with respect to other @@ -239,9 +245,11 @@ class FieldType(proto.Message): primitive_type (google.cloud.datacatalog_v1beta1.types.FieldType.PrimitiveType): Represents primitive types - string, bool etc. + This field is a member of `oneof`_ ``type_decl``. enum_type (google.cloud.datacatalog_v1beta1.types.FieldType.EnumType): Represents an enum type. + This field is a member of `oneof`_ ``type_decl``. """