From 1c03dcc182fc96a2ca85b23da99cbcaebfb3fe09 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 7 Jun 2021 00:37:20 -0400 Subject: [PATCH] feat: add progress field to UpdateDatabaseDdlMetadata (#361) * chore: fix owlbot.py to copy changes from googleapis-gen * feat(spanner): add progress field to UpdateDatabaseDdlMetadata * use the latest owlbot post processor image * chore: move import of CommitResponse * add workarounds in owlbot.py * run post processor * update owlbot.py to copy multiple folders/versions from googleapis-gen --- .github/.OwlBot.lock.yaml | 2 +- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +- docs/conf.py | 1 + docs/multiprocessing.rst | 4 +- .../database_admin.rst | 1 - docs/spanner_admin_database_v1/types.rst | 1 + .../instance_admin.rst | 1 - docs/spanner_admin_instance_v1/types.rst | 1 + docs/spanner_v1/spanner.rst | 1 - docs/spanner_v1/types.rst | 1 + .../spanner_admin_database_v1/__init__.py | 9 +- .../gapic_metadata.json | 193 +++ .../services/__init__.py | 1 - .../services/database_admin/__init__.py | 2 - .../services/database_admin/async_client.py | 142 +- .../services/database_admin/client.py | 173 +-- .../services/database_admin/pagers.py | 20 +- .../database_admin/transports/__init__.py | 2 - .../database_admin/transports/base.py | 235 +-- .../database_admin/transports/grpc.py | 75 +- .../database_admin/transports/grpc_asyncio.py | 81 +- .../types/__init__.py | 2 - .../spanner_admin_database_v1/types/backup.py | 107 +- .../spanner_admin_database_v1/types/common.py | 24 +- .../types/spanner_database_admin.py | 130 +- .../spanner_admin_instance_v1/__init__.py | 7 +- .../gapic_metadata.json | 123 ++ .../services/__init__.py | 1 - .../services/instance_admin/__init__.py | 2 - .../services/instance_admin/async_client.py | 94 +- .../services/instance_admin/client.py | 125 +- .../services/instance_admin/pagers.py | 6 +- .../instance_admin/transports/__init__.py | 2 - .../instance_admin/transports/base.py | 183 ++- .../instance_admin/transports/grpc.py | 65 +- .../instance_admin/transports/grpc_asyncio.py | 65 +- .../types/__init__.py | 2 - .../types/spanner_instance_admin.py | 99 +- google/cloud/spanner_v1/__init__.py | 2 +- google/cloud/spanner_v1/gapic_metadata.json | 173 +++ google/cloud/spanner_v1/services/__init__.py | 1 - .../spanner_v1/services/spanner/__init__.py | 2 - .../services/spanner/async_client.py | 116 +- .../spanner_v1/services/spanner/client.py | 112 +- .../spanner_v1/services/spanner/pagers.py | 4 +- .../services/spanner/transports/__init__.py | 2 - .../services/spanner/transports/base.py | 234 +-- .../services/spanner/transports/grpc.py | 41 +- .../spanner/transports/grpc_asyncio.py | 40 +- google/cloud/spanner_v1/types/__init__.py | 6 +- .../cloud/spanner_v1/types/commit_response.py | 59 + google/cloud/spanner_v1/types/keys.py | 22 +- google/cloud/spanner_v1/types/mutation.py | 23 +- google/cloud/spanner_v1/types/query_plan.py | 32 +- google/cloud/spanner_v1/types/result_set.py | 29 +- google/cloud/spanner_v1/types/spanner.py | 234 +-- google/cloud/spanner_v1/types/transaction.py | 326 ++++- google/cloud/spanner_v1/types/type.py | 8 +- noxfile.py | 2 +- owlbot.py | 87 +- samples/samples/noxfile.py | 8 +- ...ixup_spanner_admin_database_v1_keywords.py | 39 +- ...ixup_spanner_admin_instance_v1_keywords.py | 25 +- scripts/fixup_spanner_v1_keywords.py | 35 +- tests/__init__.py | 15 + tests/unit/__init__.py | 4 +- tests/unit/gapic/__init__.py | 15 + .../spanner_admin_database_v1/__init__.py | 1 - .../test_database_admin.py | 1273 +++++++++-------- .../spanner_admin_instance_v1/__init__.py | 1 - .../test_instance_admin.py | 879 +++++++----- tests/unit/gapic/spanner_v1/__init__.py | 1 - tests/unit/gapic/spanner_v1/test_spanner.py | 726 +++++----- 74 files changed, 3786 insertions(+), 2792 deletions(-) create mode 100644 google/cloud/spanner_admin_database_v1/gapic_metadata.json create mode 100644 google/cloud/spanner_admin_instance_v1/gapic_metadata.json create mode 100644 google/cloud/spanner_v1/gapic_metadata.json create mode 100644 google/cloud/spanner_v1/types/commit_response.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 29084e8a33..43adabe6a5 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,4 @@ docker: - digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 image: gcr.io/repo-automation-bots/owlbot-python:latest diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5d7..4f00c7cffc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.2 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 176f8e514e..17ee397e34 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/docs/conf.py b/docs/conf.py index f45ea05991..9703f9705e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -363,6 +363,7 @@ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst index 1cb29d4ca9..536d17b2ea 100644 --- a/docs/multiprocessing.rst +++ b/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + Because this client uses :mod:`grpc` library, it is safe to share instances across threads. In multiprocessing scenarios, the best practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/docs/spanner_admin_database_v1/database_admin.rst b/docs/spanner_admin_database_v1/database_admin.rst index 5618b72cd6..bd6aab00e4 100644 --- a/docs/spanner_admin_database_v1/database_admin.rst +++ b/docs/spanner_admin_database_v1/database_admin.rst @@ -5,7 +5,6 @@ DatabaseAdmin :members: :inherited-members: - .. automodule:: google.cloud.spanner_admin_database_v1.services.database_admin.pagers :members: :inherited-members: diff --git a/docs/spanner_admin_database_v1/types.rst b/docs/spanner_admin_database_v1/types.rst index fe6c27778b..95e1d7f88b 100644 --- a/docs/spanner_admin_database_v1/types.rst +++ b/docs/spanner_admin_database_v1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Spanner Admin Database v1 API .. automodule:: google.cloud.spanner_admin_database_v1.types :members: + :undoc-members: :show-inheritance: diff --git a/docs/spanner_admin_instance_v1/instance_admin.rst b/docs/spanner_admin_instance_v1/instance_admin.rst index f18b5ca893..fe820b3fad 100644 --- a/docs/spanner_admin_instance_v1/instance_admin.rst +++ b/docs/spanner_admin_instance_v1/instance_admin.rst @@ -5,7 +5,6 @@ InstanceAdmin :members: :inherited-members: - .. automodule:: google.cloud.spanner_admin_instance_v1.services.instance_admin.pagers :members: :inherited-members: diff --git a/docs/spanner_admin_instance_v1/types.rst b/docs/spanner_admin_instance_v1/types.rst index 250cf6bf9b..8f7204ebce 100644 --- a/docs/spanner_admin_instance_v1/types.rst +++ b/docs/spanner_admin_instance_v1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Spanner Admin Instance v1 API .. automodule:: google.cloud.spanner_admin_instance_v1.types :members: + :undoc-members: :show-inheritance: diff --git a/docs/spanner_v1/spanner.rst b/docs/spanner_v1/spanner.rst index f7803df4ae..b51f4447e4 100644 --- a/docs/spanner_v1/spanner.rst +++ b/docs/spanner_v1/spanner.rst @@ -5,7 +5,6 @@ Spanner :members: :inherited-members: - .. automodule:: google.cloud.spanner_v1.services.spanner.pagers :members: :inherited-members: diff --git a/docs/spanner_v1/types.rst b/docs/spanner_v1/types.rst index c7ff7e6c71..8678aba188 100644 --- a/docs/spanner_v1/types.rst +++ b/docs/spanner_v1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Spanner v1 API .. automodule:: google.cloud.spanner_v1.types :members: + :undoc-members: :show-inheritance: diff --git a/google/cloud/spanner_admin_database_v1/__init__.py b/google/cloud/spanner_admin_database_v1/__init__.py index dded570012..a6272a0ea2 100644 --- a/google/cloud/spanner_admin_database_v1/__init__.py +++ b/google/cloud/spanner_admin_database_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.database_admin import DatabaseAdminClient +from .services.database_admin import DatabaseAdminAsyncClient + from .types.backup import Backup from .types.backup import BackupInfo from .types.backup import CreateBackupEncryptionConfig @@ -47,12 +48,12 @@ from .types.spanner_database_admin import RestoreDatabaseMetadata from .types.spanner_database_admin import RestoreDatabaseRequest from .types.spanner_database_admin import RestoreInfo -from .types.spanner_database_admin import RestoreSourceType from .types.spanner_database_admin import UpdateDatabaseDdlMetadata from .types.spanner_database_admin import UpdateDatabaseDdlRequest - +from .types.spanner_database_admin import RestoreSourceType __all__ = ( + "DatabaseAdminAsyncClient", "Backup", "BackupInfo", "CreateBackupEncryptionConfig", @@ -61,6 +62,7 @@ "CreateDatabaseMetadata", "CreateDatabaseRequest", "Database", + "DatabaseAdminClient", "DeleteBackupRequest", "DropDatabaseRequest", "EncryptionConfig", @@ -87,5 +89,4 @@ "UpdateBackupRequest", "UpdateDatabaseDdlMetadata", "UpdateDatabaseDdlRequest", - "DatabaseAdminClient", ) diff --git a/google/cloud/spanner_admin_database_v1/gapic_metadata.json b/google/cloud/spanner_admin_database_v1/gapic_metadata.json new file mode 100644 index 0000000000..1460097dc3 --- /dev/null +++ b/google/cloud/spanner_admin_database_v1/gapic_metadata.json @@ -0,0 +1,193 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.spanner_admin_database_v1", + "protoPackage": "google.spanner.admin.database.v1", + "schema": "1.0", + "services": { + "DatabaseAdmin": { + "clients": { + "grpc": { + "libraryClient": "DatabaseAdminClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateDatabase": { + "methods": [ + "create_database" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DropDatabase": { + "methods": [ + "drop_database" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetDatabase": { + "methods": [ + "get_database" + ] + }, + "GetDatabaseDdl": { + "methods": [ + "get_database_ddl" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListBackupOperations": { + "methods": [ + "list_backup_operations" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListDatabaseOperations": { + "methods": [ + "list_database_operations" + ] + }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, + "RestoreDatabase": { + "methods": [ + "restore_database" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateDatabaseDdl": { + "methods": [ + "update_database_ddl" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DatabaseAdminAsyncClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "create_backup" + ] + }, + "CreateDatabase": { + "methods": [ + "create_database" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DropDatabase": { + "methods": [ + "drop_database" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetDatabase": { + "methods": [ + "get_database" + ] + }, + "GetDatabaseDdl": { + "methods": [ + "get_database_ddl" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListBackupOperations": { + "methods": [ + "list_backup_operations" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListDatabaseOperations": { + "methods": [ + "list_database_operations" + ] + }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, + "RestoreDatabase": { + "methods": [ + "restore_database" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateDatabaseDdl": { + "methods": [ + "update_database_ddl" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/spanner_admin_database_v1/services/__init__.py b/google/cloud/spanner_admin_database_v1/services/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/google/cloud/spanner_admin_database_v1/services/__init__.py +++ b/google/cloud/spanner_admin_database_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py b/google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py index 1fd198c176..abe449ebfa 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DatabaseAdminClient from .async_client import DatabaseAdminAsyncClient diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py b/google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py index e40e0b1960..d9178c81a4 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -35,13 +33,12 @@ from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import common from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import DatabaseAdminTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DatabaseAdminGrpcAsyncIOTransport from .client import DatabaseAdminClient @@ -73,31 +70,26 @@ class DatabaseAdminAsyncClient: parse_database_path = staticmethod(DatabaseAdminClient.parse_database_path) instance_path = staticmethod(DatabaseAdminClient.instance_path) parse_instance_path = staticmethod(DatabaseAdminClient.parse_instance_path) - common_billing_account_path = staticmethod( DatabaseAdminClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( DatabaseAdminClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DatabaseAdminClient.common_folder_path) parse_common_folder_path = staticmethod( DatabaseAdminClient.parse_common_folder_path ) - common_organization_path = staticmethod( DatabaseAdminClient.common_organization_path ) parse_common_organization_path = staticmethod( DatabaseAdminClient.parse_common_organization_path ) - common_project_path = staticmethod(DatabaseAdminClient.common_project_path) parse_common_project_path = staticmethod( DatabaseAdminClient.parse_common_project_path ) - common_location_path = staticmethod(DatabaseAdminClient.common_location_path) parse_common_location_path = staticmethod( DatabaseAdminClient.parse_common_location_path @@ -105,7 +97,8 @@ class DatabaseAdminAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -120,7 +113,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -137,7 +130,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DatabaseAdminTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: DatabaseAdminTransport: The transport used by the client instance. @@ -151,12 +144,12 @@ def transport(self) -> DatabaseAdminTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DatabaseAdminTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the database admin client. + """Instantiates the database admin client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -188,7 +181,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DatabaseAdminClient( credentials=credentials, transport=transport, @@ -219,7 +211,6 @@ async def list_databases( 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. @@ -229,7 +220,7 @@ async def list_databases( Returns: google.cloud.spanner_admin_database_v1.services.database_admin.pagers.ListDatabasesAsyncPager: The response for - [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. + [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. Iterating over this object will yield results and resolve additional pages automatically. @@ -249,7 +240,6 @@ async def list_databases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -262,7 +252,8 @@ async def list_databases( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -333,7 +324,6 @@ async def create_database( This corresponds to the ``create_statement`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -363,7 +353,6 @@ async def create_database( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if create_statement is not None: @@ -420,7 +409,6 @@ async def get_database( 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. @@ -445,7 +433,6 @@ async def get_database( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -458,7 +445,8 @@ async def get_database( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -531,7 +519,6 @@ async def update_database_ddl( This corresponds to the ``statements`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -571,10 +558,8 @@ async def update_database_ddl( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database - if statements: request.statements.extend(statements) @@ -587,7 +572,8 @@ async def update_database_ddl( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -608,7 +594,7 @@ async def update_database_ddl( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=spanner_database_admin.UpdateDatabaseDdlMetadata, ) @@ -637,7 +623,6 @@ async def drop_database( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -658,7 +643,6 @@ async def drop_database( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -671,7 +655,8 @@ async def drop_database( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -716,7 +701,6 @@ async def get_database_ddl( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -726,7 +710,7 @@ async def get_database_ddl( Returns: google.cloud.spanner_admin_database_v1.types.GetDatabaseDdlResponse: The response for - [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. + [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. """ # Create or coerce a protobuf request object. @@ -743,7 +727,6 @@ async def get_database_ddl( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -756,7 +739,8 @@ async def get_database_ddl( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -778,13 +762,13 @@ async def get_database_ddl( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on a database or backup resource. Replaces any existing policy. @@ -808,7 +792,6 @@ async def set_iam_policy( 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. @@ -887,10 +870,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -914,13 +896,13 @@ async def set_iam_policy( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a database or backup resource. Returns an empty policy if a database or backup exists but does not have a policy set. @@ -945,7 +927,6 @@ async def get_iam_policy( 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. @@ -1024,10 +1005,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1038,7 +1018,8 @@ async def get_iam_policy( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -1060,14 +1041,14 @@ async def get_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified database or backup resource. @@ -1101,7 +1082,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1125,10 +1105,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1207,7 +1186,6 @@ async def create_backup( This corresponds to the ``backup_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1237,7 +1215,6 @@ async def create_backup( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if backup is not None: @@ -1296,7 +1273,6 @@ async def get_backup( 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. @@ -1321,7 +1297,6 @@ async def get_backup( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1334,7 +1309,8 @@ async def get_backup( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -1359,7 +1335,7 @@ async def update_backup( request: gsad_backup.UpdateBackupRequest = None, *, backup: gsad_backup.Backup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1379,7 +1355,6 @@ async def update_backup( - ``backup.expire_time``. - This corresponds to the ``backup`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1395,7 +1370,6 @@ async def update_backup( 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. @@ -1420,7 +1394,6 @@ async def update_backup( # If we have keyword arguments corresponding to fields on the # request, apply these. - if backup is not None: request.backup = backup if update_mask is not None: @@ -1435,7 +1408,8 @@ async def update_backup( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -1481,7 +1455,6 @@ async def delete_backup( 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. @@ -1502,7 +1475,6 @@ async def delete_backup( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1515,7 +1487,8 @@ async def delete_backup( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -1558,7 +1531,6 @@ async def list_backups( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1568,7 +1540,7 @@ async def list_backups( Returns: google.cloud.spanner_admin_database_v1.services.database_admin.pagers.ListBackupsAsyncPager: The response for - [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. + [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. Iterating over this object will yield results and resolve additional pages automatically. @@ -1588,7 +1560,6 @@ async def list_backups( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1601,7 +1572,8 @@ async def list_backups( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -1690,7 +1662,6 @@ async def restore_database( This corresponds to the ``backup`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1720,7 +1691,6 @@ async def restore_database( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if database_id is not None: @@ -1788,7 +1758,6 @@ async def list_database_operations( 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. @@ -1818,7 +1787,6 @@ async def list_database_operations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1831,7 +1799,8 @@ async def list_database_operations( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -1891,7 +1860,6 @@ async def list_backup_operations( 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. @@ -1921,7 +1889,6 @@ async def list_backup_operations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1934,7 +1901,8 @@ async def list_backup_operations( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/client.py b/google/cloud/spanner_admin_database_v1/services/database_admin/client.py index 4dfb39e47b..47a7026339 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/client.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -39,13 +37,12 @@ from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import common from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import DatabaseAdminTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DatabaseAdminGrpcTransport from .transports.grpc_asyncio import DatabaseAdminGrpcAsyncIOTransport @@ -64,7 +61,7 @@ class DatabaseAdminClientMeta(type): _transport_registry["grpc_asyncio"] = DatabaseAdminGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[DatabaseAdminTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -93,7 +90,8 @@ class DatabaseAdminClient(metaclass=DatabaseAdminClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -127,7 +125,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -144,7 +143,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -163,23 +162,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DatabaseAdminTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DatabaseAdminTransport: The transport used by the client instance. + DatabaseAdminTransport: The transport used by the client + instance. """ return self._transport @staticmethod def backup_path(project: str, instance: str, backup: str,) -> str: - """Return a fully-qualified backup string.""" + """Returns a fully-qualified backup string.""" return "projects/{project}/instances/{instance}/backups/{backup}".format( project=project, instance=instance, backup=backup, ) @staticmethod def parse_backup_path(path: str) -> Dict[str, str]: - """Parse a backup path into its component segments.""" + """Parses a backup path into its component segments.""" m = re.match( r"^projects/(?P.+?)/instances/(?P.+?)/backups/(?P.+?)$", path, @@ -190,7 +190,7 @@ def parse_backup_path(path: str) -> Dict[str, str]: def crypto_key_path( project: str, location: str, key_ring: str, crypto_key: str, ) -> str: - """Return a fully-qualified crypto_key string.""" + """Returns a fully-qualified crypto_key string.""" return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( project=project, location=location, @@ -200,7 +200,7 @@ def crypto_key_path( @staticmethod def parse_crypto_key_path(path: str) -> Dict[str, str]: - """Parse a crypto_key path into its component segments.""" + """Parses a crypto_key path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path, @@ -215,7 +215,7 @@ def crypto_key_version_path( crypto_key: str, crypto_key_version: str, ) -> str: - """Return a fully-qualified crypto_key_version string.""" + """Returns a fully-qualified crypto_key_version string.""" return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, location=location, @@ -226,7 +226,7 @@ def crypto_key_version_path( @staticmethod def parse_crypto_key_version_path(path: str) -> Dict[str, str]: - """Parse a crypto_key_version path into its component segments.""" + """Parses a crypto_key_version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path, @@ -235,14 +235,14 @@ def parse_crypto_key_version_path(path: str) -> Dict[str, str]: @staticmethod def database_path(project: str, instance: str, database: str,) -> str: - """Return a fully-qualified database string.""" + """Returns a fully-qualified database string.""" return "projects/{project}/instances/{instance}/databases/{database}".format( project=project, instance=instance, database=database, ) @staticmethod def parse_database_path(path: str) -> Dict[str, str]: - """Parse a database path into its component segments.""" + """Parses a database path into its component segments.""" m = re.match( r"^projects/(?P.+?)/instances/(?P.+?)/databases/(?P.+?)$", path, @@ -251,20 +251,20 @@ def parse_database_path(path: str) -> Dict[str, str]: @staticmethod def instance_path(project: str, instance: str,) -> str: - """Return a fully-qualified instance string.""" + """Returns a fully-qualified instance string.""" return "projects/{project}/instances/{instance}".format( project=project, instance=instance, ) @staticmethod def parse_instance_path(path: str) -> Dict[str, str]: - """Parse a instance path into its component segments.""" + """Parses a instance path into its component segments.""" m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -277,7 +277,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -288,7 +288,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -299,7 +299,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -310,7 +310,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -324,12 +324,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DatabaseAdminTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the database admin client. + """Instantiates the database admin client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -384,9 +384,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -398,12 +399,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -418,8 +421,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -457,7 +460,6 @@ def list_databases( 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. @@ -467,7 +469,7 @@ def list_databases( Returns: google.cloud.spanner_admin_database_v1.services.database_admin.pagers.ListDatabasesPager: The response for - [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. + [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. Iterating over this object will yield results and resolve additional pages automatically. @@ -489,10 +491,8 @@ def list_databases( # there are no flattened fields. if not isinstance(request, spanner_database_admin.ListDatabasesRequest): request = spanner_database_admin.ListDatabasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -563,7 +563,6 @@ def create_database( This corresponds to the ``create_statement`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -595,10 +594,8 @@ def create_database( # there are no flattened fields. if not isinstance(request, spanner_database_admin.CreateDatabaseRequest): request = spanner_database_admin.CreateDatabaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if create_statement is not None: @@ -651,7 +648,6 @@ def get_database( 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. @@ -678,10 +674,8 @@ def get_database( # there are no flattened fields. if not isinstance(request, spanner_database_admin.GetDatabaseRequest): request = spanner_database_admin.GetDatabaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -754,7 +748,6 @@ def update_database_ddl( This corresponds to the ``statements`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -796,10 +789,8 @@ def update_database_ddl( # there are no flattened fields. if not isinstance(request, spanner_database_admin.UpdateDatabaseDdlRequest): request = spanner_database_admin.UpdateDatabaseDdlRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database if statements is not None: @@ -822,7 +813,7 @@ def update_database_ddl( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=spanner_database_admin.UpdateDatabaseDdlMetadata, ) @@ -851,7 +842,6 @@ def drop_database( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -874,10 +864,8 @@ def drop_database( # there are no flattened fields. if not isinstance(request, spanner_database_admin.DropDatabaseRequest): request = spanner_database_admin.DropDatabaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -922,7 +910,6 @@ def get_database_ddl( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -932,7 +919,7 @@ def get_database_ddl( Returns: google.cloud.spanner_admin_database_v1.types.GetDatabaseDdlResponse: The response for - [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. + [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. """ # Create or coerce a protobuf request object. @@ -951,10 +938,8 @@ def get_database_ddl( # there are no flattened fields. if not isinstance(request, spanner_database_admin.GetDatabaseDdlRequest): request = spanner_database_admin.GetDatabaseDdlRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -976,13 +961,13 @@ def get_database_ddl( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on a database or backup resource. Replaces any existing policy. @@ -1006,7 +991,6 @@ def set_iam_policy( 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. @@ -1085,11 +1069,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1111,13 +1094,13 @@ def set_iam_policy( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a database or backup resource. Returns an empty policy if a database or backup exists but does not have a policy set. @@ -1142,7 +1125,6 @@ def get_iam_policy( 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. @@ -1221,11 +1203,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1247,14 +1228,14 @@ def get_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified database or backup resource. @@ -1288,7 +1269,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1312,14 +1292,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) @@ -1394,7 +1372,6 @@ def create_backup( This corresponds to the ``backup_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1426,10 +1403,8 @@ def create_backup( # there are no flattened fields. if not isinstance(request, gsad_backup.CreateBackupRequest): request = gsad_backup.CreateBackupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if backup is not None: @@ -1484,7 +1459,6 @@ def get_backup( 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. @@ -1511,10 +1485,8 @@ def get_backup( # there are no flattened fields. if not isinstance(request, backup.GetBackupRequest): request = backup.GetBackupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1539,7 +1511,7 @@ def update_backup( request: gsad_backup.UpdateBackupRequest = None, *, backup: gsad_backup.Backup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1559,7 +1531,6 @@ def update_backup( - ``backup.expire_time``. - This corresponds to the ``backup`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1575,7 +1546,6 @@ def update_backup( 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. @@ -1602,10 +1572,8 @@ def update_backup( # there are no flattened fields. if not isinstance(request, gsad_backup.UpdateBackupRequest): request = gsad_backup.UpdateBackupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if backup is not None: request.backup = backup if update_mask is not None: @@ -1653,7 +1621,6 @@ def delete_backup( 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. @@ -1676,10 +1643,8 @@ def delete_backup( # there are no flattened fields. if not isinstance(request, backup.DeleteBackupRequest): request = backup.DeleteBackupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1722,7 +1687,6 @@ def list_backups( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1732,7 +1696,7 @@ def list_backups( Returns: google.cloud.spanner_admin_database_v1.services.database_admin.pagers.ListBackupsPager: The response for - [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. + [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. Iterating over this object will yield results and resolve additional pages automatically. @@ -1754,10 +1718,8 @@ def list_backups( # there are no flattened fields. if not isinstance(request, backup.ListBackupsRequest): request = backup.ListBackupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1846,7 +1808,6 @@ def restore_database( This corresponds to the ``backup`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1878,10 +1839,8 @@ def restore_database( # there are no flattened fields. if not isinstance(request, spanner_database_admin.RestoreDatabaseRequest): request = spanner_database_admin.RestoreDatabaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if database_id is not None: @@ -1945,7 +1904,6 @@ def list_database_operations( 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. @@ -1979,10 +1937,8 @@ def list_database_operations( request, spanner_database_admin.ListDatabaseOperationsRequest ): request = spanner_database_admin.ListDatabaseOperationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -2042,7 +1998,6 @@ def list_backup_operations( 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. @@ -2074,10 +2029,8 @@ def list_backup_operations( # there are no flattened fields. if not isinstance(request, backup.ListBackupOperationsRequest): request = backup.ListBackupOperationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py b/google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py index 933ca91c5a..552f761751 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -28,7 +26,7 @@ from google.cloud.spanner_admin_database_v1.types import backup from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.longrunning import operations_pb2 as operations # type: ignore +from google.longrunning import operations_pb2 # type: ignore class ListDatabasesPager: @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -249,7 +247,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -343,7 +341,7 @@ def pages(self) -> Iterable[spanner_database_admin.ListDatabaseOperationsRespons self._response = self._method(self._request, metadata=self._metadata) yield self._response - def __iter__(self) -> Iterable[operations.Operation]: + def __iter__(self) -> Iterable[operations_pb2.Operation]: for page in self.pages: yield from page.operations @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -409,7 +407,7 @@ async def pages( self._response = await self._method(self._request, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterable[operations.Operation]: + def __aiter__(self) -> AsyncIterable[operations_pb2.Operation]: async def async_generator(): async for page in self.pages: for response in page.operations: @@ -475,7 +473,7 @@ def pages(self) -> Iterable[backup.ListBackupOperationsResponse]: self._response = self._method(self._request, metadata=self._metadata) yield self._response - def __iter__(self) -> Iterable[operations.Operation]: + def __iter__(self) -> Iterable[operations_pb2.Operation]: for page in self.pages: yield from page.operations @@ -509,7 +507,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -537,7 +535,7 @@ async def pages(self) -> AsyncIterable[backup.ListBackupOperationsResponse]: self._response = await self._method(self._request, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterable[operations.Operation]: + def __aiter__(self) -> AsyncIterable[operations_pb2.Operation]: async def async_generator(): async for page in self.pages: for response in page.operations: diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py index 00a3ab8549..743a749bfa 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py index 0e9a7e50c7..66574db79c 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,26 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.spanner_admin_database_v1.types import backup from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -44,6 +43,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class DatabaseAdminTransport(abc.ABC): """Abstract transport class for DatabaseAdmin.""" @@ -53,21 +63,24 @@ class DatabaseAdminTransport(abc.ABC): "https://www.googleapis.com/auth/spanner.admin", ) + DEFAULT_HOST: str = "spanner.googleapis.com" + def __init__( self, *, - host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -76,7 +89,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -90,29 +103,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -123,7 +183,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -140,7 +201,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -154,7 +216,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -168,7 +231,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -182,7 +246,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -199,7 +264,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -221,7 +287,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -235,7 +302,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -249,7 +317,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -263,7 +332,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -280,7 +350,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -294,7 +365,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -311,11 +383,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_databases( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.ListDatabasesRequest], - typing.Union[ + Union[ spanner_database_admin.ListDatabasesResponse, - typing.Awaitable[spanner_database_admin.ListDatabasesResponse], + Awaitable[spanner_database_admin.ListDatabasesResponse], ], ]: raise NotImplementedError() @@ -323,20 +395,19 @@ def list_databases( @property def create_database( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.CreateDatabaseRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def get_database( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.GetDatabaseRequest], - typing.Union[ - spanner_database_admin.Database, - typing.Awaitable[spanner_database_admin.Database], + Union[ + spanner_database_admin.Database, Awaitable[spanner_database_admin.Database] ], ]: raise NotImplementedError() @@ -344,29 +415,29 @@ def get_database( @property def update_database_ddl( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.UpdateDatabaseDdlRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def drop_database( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.DropDatabaseRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_database_ddl( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.GetDatabaseDdlRequest], - typing.Union[ + Union[ spanner_database_admin.GetDatabaseDdlResponse, - typing.Awaitable[spanner_database_admin.GetDatabaseDdlResponse], + Awaitable[spanner_database_admin.GetDatabaseDdlResponse], ], ]: raise NotImplementedError() @@ -374,29 +445,29 @@ def get_database_ddl( @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() @@ -404,67 +475,63 @@ def test_iam_permissions( @property def create_backup( self, - ) -> typing.Callable[ + ) -> Callable[ [gsad_backup.CreateBackupRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def get_backup( self, - ) -> typing.Callable[ - [backup.GetBackupRequest], - typing.Union[backup.Backup, typing.Awaitable[backup.Backup]], + ) -> Callable[ + [backup.GetBackupRequest], Union[backup.Backup, Awaitable[backup.Backup]] ]: raise NotImplementedError() @property def update_backup( self, - ) -> typing.Callable[ + ) -> Callable[ [gsad_backup.UpdateBackupRequest], - typing.Union[gsad_backup.Backup, typing.Awaitable[gsad_backup.Backup]], + Union[gsad_backup.Backup, Awaitable[gsad_backup.Backup]], ]: raise NotImplementedError() @property def delete_backup( self, - ) -> typing.Callable[ - [backup.DeleteBackupRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [backup.DeleteBackupRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def list_backups( self, - ) -> typing.Callable[ + ) -> Callable[ [backup.ListBackupsRequest], - typing.Union[ - backup.ListBackupsResponse, typing.Awaitable[backup.ListBackupsResponse] - ], + Union[backup.ListBackupsResponse, Awaitable[backup.ListBackupsResponse]], ]: raise NotImplementedError() @property def restore_database( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.RestoreDatabaseRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def list_database_operations( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_database_admin.ListDatabaseOperationsRequest], - typing.Union[ + Union[ spanner_database_admin.ListDatabaseOperationsResponse, - typing.Awaitable[spanner_database_admin.ListDatabaseOperationsResponse], + Awaitable[spanner_database_admin.ListDatabaseOperationsResponse], ], ]: raise NotImplementedError() @@ -472,11 +539,11 @@ def list_database_operations( @property def list_backup_operations( self, - ) -> typing.Callable[ + ) -> Callable[ [backup.ListBackupOperationsRequest], - typing.Union[ + Union[ backup.ListBackupOperationsResponse, - typing.Awaitable[backup.ListBackupOperationsResponse], + Awaitable[backup.ListBackupOperationsResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py index b695a5a113..043d5fd1c2 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,11 +28,10 @@ from google.cloud.spanner_admin_database_v1.types import backup from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import DatabaseAdminTransport, DEFAULT_CLIENT_INFO @@ -62,7 +59,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -76,7 +73,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -187,7 +185,7 @@ def __init__( def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -218,13 +216,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -280,7 +280,9 @@ def list_databases( @property def create_database( self, - ) -> Callable[[spanner_database_admin.CreateDatabaseRequest], operations.Operation]: + ) -> Callable[ + [spanner_database_admin.CreateDatabaseRequest], operations_pb2.Operation + ]: r"""Return a callable for the create database method over gRPC. Creates a new Cloud Spanner database and starts to prepare it @@ -308,7 +310,7 @@ def create_database( self._stubs["create_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/CreateDatabase", request_serializer=spanner_database_admin.CreateDatabaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_database"] @@ -344,7 +346,7 @@ def get_database( def update_database_ddl( self, ) -> Callable[ - [spanner_database_admin.UpdateDatabaseDdlRequest], operations.Operation + [spanner_database_admin.UpdateDatabaseDdlRequest], operations_pb2.Operation ]: r"""Return a callable for the update database ddl method over gRPC. @@ -372,14 +374,14 @@ def update_database_ddl( self._stubs["update_database_ddl"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/UpdateDatabaseDdl", request_serializer=spanner_database_admin.UpdateDatabaseDdlRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_database_ddl"] @property def drop_database( self, - ) -> Callable[[spanner_database_admin.DropDatabaseRequest], empty.Empty]: + ) -> Callable[[spanner_database_admin.DropDatabaseRequest], empty_pb2.Empty]: r"""Return a callable for the drop database method over gRPC. Drops (aka deletes) a Cloud Spanner database. Completed backups @@ -400,7 +402,7 @@ def drop_database( self._stubs["drop_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/DropDatabase", request_serializer=spanner_database_admin.DropDatabaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["drop_database"] @@ -439,7 +441,7 @@ def get_database_ddl( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> 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 on a database or backup resource. @@ -465,15 +467,15 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], policy.Policy]: + ) -> 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 database or backup @@ -500,8 +502,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -509,7 +511,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -537,15 +540,15 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] @property def create_backup( self, - ) -> Callable[[gsad_backup.CreateBackupRequest], operations.Operation]: + ) -> Callable[[gsad_backup.CreateBackupRequest], operations_pb2.Operation]: r"""Return a callable for the create backup method over gRPC. Starts creating a new Cloud Spanner Backup. The returned backup @@ -576,7 +579,7 @@ def create_backup( self._stubs["create_backup"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/CreateBackup", request_serializer=gsad_backup.CreateBackupRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_backup"] @@ -633,7 +636,7 @@ def update_backup( return self._stubs["update_backup"] @property - def delete_backup(self) -> Callable[[backup.DeleteBackupRequest], empty.Empty]: + def delete_backup(self) -> Callable[[backup.DeleteBackupRequest], empty_pb2.Empty]: r"""Return a callable for the delete backup method over gRPC. Deletes a pending or completed @@ -653,7 +656,7 @@ def delete_backup(self) -> Callable[[backup.DeleteBackupRequest], empty.Empty]: self._stubs["delete_backup"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/DeleteBackup", request_serializer=backup.DeleteBackupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_backup"] @@ -689,7 +692,7 @@ def list_backups( def restore_database( self, ) -> Callable[ - [spanner_database_admin.RestoreDatabaseRequest], operations.Operation + [spanner_database_admin.RestoreDatabaseRequest], operations_pb2.Operation ]: r"""Return a callable for the restore database method over gRPC. @@ -727,7 +730,7 @@ def restore_database( self._stubs["restore_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/RestoreDatabase", request_serializer=spanner_database_admin.RestoreDatabaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_database"] diff --git a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py index cac4b1e2b6..9ca356617f 100644 --- a/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py +++ b/google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,15 @@ # 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 +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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,11 +29,10 @@ from google.cloud.spanner_admin_database_v1.types import backup from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import DatabaseAdminTransport, DEFAULT_CLIENT_INFO from .grpc import DatabaseAdminGrpcTransport @@ -65,7 +62,7 @@ class DatabaseAdminGrpcAsyncIOTransport(DatabaseAdminTransport): def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -92,13 +89,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -106,7 +105,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -120,7 +119,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -179,7 +179,6 @@ def __init__( # 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 @@ -287,7 +286,8 @@ def list_databases( def create_database( self, ) -> Callable[ - [spanner_database_admin.CreateDatabaseRequest], Awaitable[operations.Operation] + [spanner_database_admin.CreateDatabaseRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the create database method over gRPC. @@ -316,7 +316,7 @@ def create_database( self._stubs["create_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/CreateDatabase", request_serializer=spanner_database_admin.CreateDatabaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_database"] @@ -354,7 +354,7 @@ def update_database_ddl( self, ) -> Callable[ [spanner_database_admin.UpdateDatabaseDdlRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the update database ddl method over gRPC. @@ -382,14 +382,16 @@ def update_database_ddl( self._stubs["update_database_ddl"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/UpdateDatabaseDdl", request_serializer=spanner_database_admin.UpdateDatabaseDdlRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_database_ddl"] @property def drop_database( self, - ) -> Callable[[spanner_database_admin.DropDatabaseRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [spanner_database_admin.DropDatabaseRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the drop database method over gRPC. Drops (aka deletes) a Cloud Spanner database. Completed backups @@ -410,7 +412,7 @@ def drop_database( self._stubs["drop_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/DropDatabase", request_serializer=spanner_database_admin.DropDatabaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["drop_database"] @@ -449,7 +451,7 @@ def get_database_ddl( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 on a database or backup resource. @@ -475,15 +477,15 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 database or backup @@ -510,8 +512,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -519,8 +521,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -548,15 +550,17 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] @property def create_backup( self, - ) -> Callable[[gsad_backup.CreateBackupRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [gsad_backup.CreateBackupRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create backup method over gRPC. Starts creating a new Cloud Spanner Backup. The returned backup @@ -587,7 +591,7 @@ def create_backup( self._stubs["create_backup"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/CreateBackup", request_serializer=gsad_backup.CreateBackupRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_backup"] @@ -648,7 +652,7 @@ def update_backup( @property def delete_backup( self, - ) -> Callable[[backup.DeleteBackupRequest], Awaitable[empty.Empty]]: + ) -> Callable[[backup.DeleteBackupRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete backup method over gRPC. Deletes a pending or completed @@ -668,7 +672,7 @@ def delete_backup( self._stubs["delete_backup"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/DeleteBackup", request_serializer=backup.DeleteBackupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_backup"] @@ -704,7 +708,8 @@ def list_backups( def restore_database( self, ) -> Callable[ - [spanner_database_admin.RestoreDatabaseRequest], Awaitable[operations.Operation] + [spanner_database_admin.RestoreDatabaseRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the restore database method over gRPC. @@ -742,7 +747,7 @@ def restore_database( self._stubs["restore_database"] = self.grpc_channel.unary_unary( "/google.spanner.admin.database.v1.DatabaseAdmin/RestoreDatabase", request_serializer=spanner_database_admin.RestoreDatabaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_database"] diff --git a/google/cloud/spanner_admin_database_v1/types/__init__.py b/google/cloud/spanner_admin_database_v1/types/__init__.py index a1316e789a..1c31fe536e 100644 --- a/google/cloud/spanner_admin_database_v1/types/__init__.py +++ b/google/cloud/spanner_admin_database_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .backup import ( Backup, BackupInfo, diff --git a/google/cloud/spanner_admin_database_v1/types/backup.py b/google/cloud/spanner_admin_database_v1/types/backup.py index 7d95a007f4..0ddc815570 100644 --- a/google/cloud/spanner_admin_database_v1/types/backup.py +++ b/google/cloud/spanner_admin_database_v1/types/backup.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.spanner_admin_database_v1.types import common -from google.longrunning import operations_pb2 as gl_operations # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,7 +42,6 @@ class Backup(proto.Message): r"""A backup of a Cloud Spanner database. - Attributes: database (str): Required for the @@ -115,22 +111,16 @@ class State(proto.Enum): CREATING = 1 READY = 2 - database = proto.Field(proto.STRING, number=2) - - version_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - name = proto.Field(proto.STRING, number=1) - - create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - size_bytes = proto.Field(proto.INT64, number=5) - + database = proto.Field(proto.STRING, number=2,) + version_time = proto.Field( + proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + name = proto.Field(proto.STRING, number=1,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + size_bytes = proto.Field(proto.INT64, number=5,) state = proto.Field(proto.ENUM, number=6, enum=State,) - - referencing_databases = proto.RepeatedField(proto.STRING, number=7) - + referencing_databases = proto.RepeatedField(proto.STRING, number=7,) encryption_info = proto.Field( proto.MESSAGE, number=8, message=common.EncryptionInfo, ) @@ -164,12 +154,9 @@ class CreateBackupRequest(proto.Message): = ``USE_DATABASE_ENCRYPTION``. """ - parent = proto.Field(proto.STRING, number=1) - - backup_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + backup_id = proto.Field(proto.STRING, number=2,) backup = proto.Field(proto.MESSAGE, number=3, message="Backup",) - encryption_config = proto.Field( proto.MESSAGE, number=4, message="CreateBackupEncryptionConfig", ) @@ -206,13 +193,10 @@ class CreateBackupMetadata(proto.Message): 1, corresponding to ``Code.CANCELLED``. """ - name = proto.Field(proto.STRING, number=1) - - database = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + database = proto.Field(proto.STRING, number=2,) progress = proto.Field(proto.MESSAGE, number=3, message=common.OperationProgress,) - - cancel_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + cancel_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) class UpdateBackupRequest(proto.Message): @@ -237,8 +221,9 @@ class UpdateBackupRequest(proto.Message): """ backup = proto.Field(proto.MESSAGE, number=1, message="Backup",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class GetBackupRequest(proto.Message): @@ -251,7 +236,7 @@ class GetBackupRequest(proto.Message): ``projects//instances//backups/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteBackupRequest(proto.Message): @@ -265,7 +250,7 @@ class DeleteBackupRequest(proto.Message): ``projects//instances//backups/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListBackupsRequest(proto.Message): @@ -335,13 +320,10 @@ class ListBackupsRequest(proto.Message): to the same ``parent`` and with the same ``filter``. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListBackupsResponse(proto.Message): @@ -364,8 +346,7 @@ def raw_page(self): return self backups = proto.RepeatedField(proto.MESSAGE, number=1, message="Backup",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListBackupOperationsRequest(proto.Message): @@ -437,13 +418,10 @@ class ListBackupOperationsRequest(proto.Message): to the same ``parent`` and with the same ``filter``. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListBackupOperationsResponse(proto.Message): @@ -476,15 +454,13 @@ def raw_page(self): return self operations = proto.RepeatedField( - proto.MESSAGE, number=1, message=gl_operations.Operation, + proto.MESSAGE, number=1, message=operations_pb2.Operation, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class BackupInfo(proto.Message): r"""Information about a backup. - Attributes: backup (str): Name of the backup. @@ -505,18 +481,16 @@ class BackupInfo(proto.Message): from. """ - backup = proto.Field(proto.STRING, number=1) - - version_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - source_database = proto.Field(proto.STRING, number=3) + backup = proto.Field(proto.STRING, number=1,) + version_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + source_database = proto.Field(proto.STRING, number=3,) class CreateBackupEncryptionConfig(proto.Message): r"""Encryption configuration for the backup to create. - Attributes: encryption_type (google.cloud.spanner_admin_database_v1.types.CreateBackupEncryptionConfig.EncryptionType): Required. The encryption type of the backup. @@ -536,8 +510,7 @@ class EncryptionType(proto.Enum): CUSTOMER_MANAGED_ENCRYPTION = 3 encryption_type = proto.Field(proto.ENUM, number=1, enum=EncryptionType,) - - kms_key_name = proto.Field(proto.STRING, number=2) + kms_key_name = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_admin_database_v1/types/common.py b/google/cloud/spanner_admin_database_v1/types/common.py index 2f552d19fd..38020dcd4e 100644 --- a/google/cloud/spanner_admin_database_v1/types/common.py +++ b/google/cloud/spanner_admin_database_v1/types/common.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -43,16 +40,13 @@ class OperationProgress(proto.Message): failed or was completed successfully. """ - progress_percent = proto.Field(proto.INT32, number=1) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + progress_percent = proto.Field(proto.INT32, number=1,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class EncryptionConfig(proto.Message): r"""Encryption configuration for a Cloud Spanner database. - Attributes: kms_key_name (str): The Cloud KMS key to be used for encrypting and decrypting @@ -60,7 +54,7 @@ class EncryptionConfig(proto.Message): ``projects//locations//keyRings//cryptoKeys/``. """ - kms_key_name = proto.Field(proto.STRING, number=2) + kms_key_name = proto.Field(proto.STRING, number=2,) class EncryptionInfo(proto.Message): @@ -87,10 +81,8 @@ class Type(proto.Enum): CUSTOMER_MANAGED_ENCRYPTION = 2 encryption_type = proto.Field(proto.ENUM, number=3, enum=Type,) - - encryption_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) - - kms_key_version = proto.Field(proto.STRING, number=2) + encryption_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) + kms_key_version = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py b/google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py index 278d5e6b95..5824f575a5 100644 --- a/google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py +++ b/google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import common -from google.longrunning import operations_pb2 as gl_operations # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -58,7 +55,6 @@ class RestoreSourceType(proto.Enum): class RestoreInfo(proto.Message): r"""Information about the database restore. - Attributes: source_type (google.cloud.spanner_admin_database_v1.types.RestoreSourceType): The type of the restore source. @@ -68,7 +64,6 @@ class RestoreInfo(proto.Message): """ source_type = proto.Field(proto.ENUM, number=1, enum="RestoreSourceType",) - backup_info = proto.Field( proto.MESSAGE, number=2, oneof="source_info", message=gsad_backup.BackupInfo, ) @@ -76,7 +71,6 @@ class RestoreInfo(proto.Message): class Database(proto.Message): r"""A Cloud Spanner database. - Attributes: name (str): Required. The name of the database. Values are of the form @@ -136,26 +130,19 @@ class State(proto.Enum): READY = 2 READY_OPTIMIZING = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=State,) - - create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) restore_info = proto.Field(proto.MESSAGE, number=4, message="RestoreInfo",) - encryption_config = proto.Field( proto.MESSAGE, number=5, message=common.EncryptionConfig, ) - encryption_info = proto.RepeatedField( proto.MESSAGE, number=8, message=common.EncryptionInfo, ) - - version_retention_period = proto.Field(proto.STRING, number=6) - + version_retention_period = proto.Field(proto.STRING, number=6,) earliest_version_time = proto.Field( - proto.MESSAGE, number=7, message=timestamp.Timestamp, + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp, ) @@ -179,11 +166,9 @@ class ListDatabasesRequest(proto.Message): [ListDatabasesResponse][google.spanner.admin.database.v1.ListDatabasesResponse]. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListDatabasesResponse(proto.Message): @@ -204,8 +189,7 @@ def raw_page(self): return self databases = proto.RepeatedField(proto.MESSAGE, number=1, message="Database",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateDatabaseRequest(proto.Message): @@ -238,12 +222,9 @@ class CreateDatabaseRequest(proto.Message): rest using Google default encryption. """ - parent = proto.Field(proto.STRING, number=1) - - create_statement = proto.Field(proto.STRING, number=2) - - extra_statements = proto.RepeatedField(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + create_statement = proto.Field(proto.STRING, number=2,) + extra_statements = proto.RepeatedField(proto.STRING, number=3,) encryption_config = proto.Field( proto.MESSAGE, number=4, message=common.EncryptionConfig, ) @@ -258,7 +239,7 @@ class CreateDatabaseMetadata(proto.Message): The database being created. """ - database = proto.Field(proto.STRING, number=1) + database = proto.Field(proto.STRING, number=1,) class GetDatabaseRequest(proto.Message): @@ -272,7 +253,7 @@ class GetDatabaseRequest(proto.Message): ``projects//instances//databases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateDatabaseDdlRequest(proto.Message): @@ -323,11 +304,9 @@ class UpdateDatabaseDdlRequest(proto.Message): returns ``ALREADY_EXISTS``. """ - database = proto.Field(proto.STRING, number=1) - - statements = proto.RepeatedField(proto.STRING, number=2) - - operation_id = proto.Field(proto.STRING, number=3) + database = proto.Field(proto.STRING, number=1,) + statements = proto.RepeatedField(proto.STRING, number=2,) + operation_id = proto.Field(proto.STRING, number=3,) class UpdateDatabaseDdlMetadata(proto.Message): @@ -351,17 +330,27 @@ class UpdateDatabaseDdlMetadata(proto.Message): constraints. When resources become available the operation will resume and this field will be false again. + progress (Sequence[google.cloud.spanner_admin_database_v1.types.OperationProgress]): + The progress of the + [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] + operations. Currently, only index creation statements will + have a continuously updating progress. For non-index + creation statements, ``progress[i]`` will have start time + and end time populated with commit timestamp of operation, + as well as a progress of 100% once the operation has + completed. ``progress[i]`` is the operation progress for + ``statements[i]``. """ - database = proto.Field(proto.STRING, number=1) - - statements = proto.RepeatedField(proto.STRING, number=2) - + database = proto.Field(proto.STRING, number=1,) + statements = proto.RepeatedField(proto.STRING, number=2,) commit_timestamps = proto.RepeatedField( - proto.MESSAGE, number=3, message=timestamp.Timestamp, + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + throttled = proto.Field(proto.BOOL, number=4,) + progress = proto.RepeatedField( + proto.MESSAGE, number=5, message=common.OperationProgress, ) - - throttled = proto.Field(proto.BOOL, number=4) class DropDatabaseRequest(proto.Message): @@ -373,7 +362,7 @@ class DropDatabaseRequest(proto.Message): Required. The database to be dropped. """ - database = proto.Field(proto.STRING, number=1) + database = proto.Field(proto.STRING, number=1,) class GetDatabaseDdlRequest(proto.Message): @@ -387,7 +376,7 @@ class GetDatabaseDdlRequest(proto.Message): ``projects//instances//databases/`` """ - database = proto.Field(proto.STRING, number=1) + database = proto.Field(proto.STRING, number=1,) class GetDatabaseDdlResponse(proto.Message): @@ -401,7 +390,7 @@ class GetDatabaseDdlResponse(proto.Message): request. """ - statements = proto.RepeatedField(proto.STRING, number=1) + statements = proto.RepeatedField(proto.STRING, number=1,) class ListDatabaseOperationsRequest(proto.Message): @@ -474,13 +463,10 @@ class ListDatabaseOperationsRequest(proto.Message): to the same ``parent`` and with the same ``filter``. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListDatabaseOperationsResponse(proto.Message): @@ -506,10 +492,9 @@ def raw_page(self): return self operations = proto.RepeatedField( - proto.MESSAGE, number=1, message=gl_operations.Operation, + proto.MESSAGE, number=1, message=operations_pb2.Operation, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class RestoreDatabaseRequest(proto.Message): @@ -543,12 +528,9 @@ class RestoreDatabaseRequest(proto.Message): = ``USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION``. """ - parent = proto.Field(proto.STRING, number=1) - - database_id = proto.Field(proto.STRING, number=2) - - backup = proto.Field(proto.STRING, number=3, oneof="source") - + parent = proto.Field(proto.STRING, number=1,) + database_id = proto.Field(proto.STRING, number=2,) + backup = proto.Field(proto.STRING, number=3, oneof="source",) encryption_config = proto.Field( proto.MESSAGE, number=4, message="RestoreDatabaseEncryptionConfig", ) @@ -556,7 +538,6 @@ class RestoreDatabaseRequest(proto.Message): class RestoreDatabaseEncryptionConfig(proto.Message): r"""Encryption configuration for the restored database. - Attributes: encryption_type (google.cloud.spanner_admin_database_v1.types.RestoreDatabaseEncryptionConfig.EncryptionType): Required. The encryption type of the restored @@ -578,8 +559,7 @@ class EncryptionType(proto.Enum): CUSTOMER_MANAGED_ENCRYPTION = 3 encryption_type = proto.Field(proto.ENUM, number=1, enum=EncryptionType,) - - kms_key_name = proto.Field(proto.STRING, number=2) + kms_key_name = proto.Field(proto.STRING, number=2,) class RestoreDatabaseMetadata(proto.Message): @@ -630,19 +610,14 @@ class RestoreDatabaseMetadata(proto.Message): if the restore was not successful. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) source_type = proto.Field(proto.ENUM, number=2, enum="RestoreSourceType",) - backup_info = proto.Field( proto.MESSAGE, number=3, oneof="source_info", message=gsad_backup.BackupInfo, ) - progress = proto.Field(proto.MESSAGE, number=4, message=common.OperationProgress,) - - cancel_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - optimize_database_operation_name = proto.Field(proto.STRING, number=6) + cancel_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + optimize_database_operation_name = proto.Field(proto.STRING, number=6,) class OptimizeRestoredDatabaseMetadata(proto.Message): @@ -661,8 +636,7 @@ class OptimizeRestoredDatabaseMetadata(proto.Message): optimizations. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) progress = proto.Field(proto.MESSAGE, number=2, message=common.OperationProgress,) diff --git a/google/cloud/spanner_admin_instance_v1/__init__.py b/google/cloud/spanner_admin_instance_v1/__init__.py index 47ef07bd53..cdc373bcff 100644 --- a/google/cloud/spanner_admin_instance_v1/__init__.py +++ b/google/cloud/spanner_admin_instance_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.instance_admin import InstanceAdminClient +from .services.instance_admin import InstanceAdminAsyncClient + from .types.spanner_instance_admin import CreateInstanceMetadata from .types.spanner_instance_admin import CreateInstanceRequest from .types.spanner_instance_admin import DeleteInstanceRequest @@ -31,14 +32,15 @@ from .types.spanner_instance_admin import UpdateInstanceMetadata from .types.spanner_instance_admin import UpdateInstanceRequest - __all__ = ( + "InstanceAdminAsyncClient", "CreateInstanceMetadata", "CreateInstanceRequest", "DeleteInstanceRequest", "GetInstanceConfigRequest", "GetInstanceRequest", "Instance", + "InstanceAdminClient", "InstanceConfig", "ListInstanceConfigsRequest", "ListInstanceConfigsResponse", @@ -47,5 +49,4 @@ "ReplicaInfo", "UpdateInstanceMetadata", "UpdateInstanceRequest", - "InstanceAdminClient", ) diff --git a/google/cloud/spanner_admin_instance_v1/gapic_metadata.json b/google/cloud/spanner_admin_instance_v1/gapic_metadata.json new file mode 100644 index 0000000000..6fee5bcd53 --- /dev/null +++ b/google/cloud/spanner_admin_instance_v1/gapic_metadata.json @@ -0,0 +1,123 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.spanner_admin_instance_v1", + "protoPackage": "google.spanner.admin.instance.v1", + "schema": "1.0", + "services": { + "InstanceAdmin": { + "clients": { + "grpc": { + "libraryClient": "InstanceAdminClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetInstanceConfig": { + "methods": [ + "get_instance_config" + ] + }, + "ListInstanceConfigs": { + "methods": [ + "list_instance_configs" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + } + } + }, + "grpc-async": { + "libraryClient": "InstanceAdminAsyncClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetInstanceConfig": { + "methods": [ + "get_instance_config" + ] + }, + "ListInstanceConfigs": { + "methods": [ + "list_instance_configs" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/spanner_admin_instance_v1/services/__init__.py b/google/cloud/spanner_admin_instance_v1/services/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/google/cloud/spanner_admin_instance_v1/services/__init__.py +++ b/google/cloud/spanner_admin_instance_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py index 88c7894332..2ba47af654 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstanceAdminClient from .async_client import InstanceAdminAsyncClient diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py index f2a9c36243..2b52431771 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,20 +20,19 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.spanner_admin_instance_v1.services.instance_admin import pagers from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore - +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 InstanceAdminTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import InstanceAdminGrpcAsyncIOTransport from .client import InstanceAdminClient @@ -76,31 +73,26 @@ class InstanceAdminAsyncClient: parse_instance_config_path = staticmethod( InstanceAdminClient.parse_instance_config_path ) - common_billing_account_path = staticmethod( InstanceAdminClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( InstanceAdminClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(InstanceAdminClient.common_folder_path) parse_common_folder_path = staticmethod( InstanceAdminClient.parse_common_folder_path ) - common_organization_path = staticmethod( InstanceAdminClient.common_organization_path ) parse_common_organization_path = staticmethod( InstanceAdminClient.parse_common_organization_path ) - common_project_path = staticmethod(InstanceAdminClient.common_project_path) parse_common_project_path = staticmethod( InstanceAdminClient.parse_common_project_path ) - common_location_path = staticmethod(InstanceAdminClient.common_location_path) parse_common_location_path = staticmethod( InstanceAdminClient.parse_common_location_path @@ -108,7 +100,8 @@ class InstanceAdminAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -123,7 +116,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -140,7 +133,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstanceAdminTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: InstanceAdminTransport: The transport used by the client instance. @@ -154,12 +147,12 @@ def transport(self) -> InstanceAdminTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, InstanceAdminTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instance admin client. + """Instantiates the instance admin client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -191,7 +184,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = InstanceAdminClient( credentials=credentials, transport=transport, @@ -223,7 +215,6 @@ async def list_instance_configs( 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. @@ -253,7 +244,6 @@ async def list_instance_configs( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -266,7 +256,8 @@ async def list_instance_configs( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -316,7 +307,6 @@ async def get_instance_config( 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. @@ -345,7 +335,6 @@ async def get_instance_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -358,7 +347,8 @@ async def get_instance_config( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -401,7 +391,6 @@ async def list_instances( 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. @@ -431,7 +420,6 @@ async def list_instances( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -444,7 +432,8 @@ async def list_instances( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -492,7 +481,6 @@ async def get_instance( 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. @@ -520,7 +508,6 @@ async def get_instance( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -533,7 +520,8 @@ async def get_instance( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -630,7 +618,6 @@ async def create_instance( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -661,7 +648,6 @@ async def create_instance( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if instance_id is not None: @@ -702,7 +688,7 @@ async def update_instance( request: spanner_instance_admin.UpdateInstanceRequest = None, *, instance: spanner_instance_admin.Instance = None, - field_mask: gp_field_mask.FieldMask = None, + field_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -779,7 +765,6 @@ async def update_instance( This corresponds to the ``field_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. @@ -810,7 +795,6 @@ async def update_instance( # If we have keyword arguments corresponding to fields on the # request, apply these. - if instance is not None: request.instance = instance if field_mask is not None: @@ -879,7 +863,6 @@ async def delete_instance( 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. @@ -900,7 +883,6 @@ async def delete_instance( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -913,7 +895,8 @@ async def delete_instance( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -934,13 +917,13 @@ async def delete_instance( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on an instance resource. Replaces any existing policy. @@ -960,7 +943,6 @@ async def set_iam_policy( 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. @@ -1039,10 +1021,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1066,13 +1047,13 @@ async def set_iam_policy( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. @@ -1093,7 +1074,6 @@ async def get_iam_policy( 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. @@ -1172,10 +1152,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1186,7 +1165,8 @@ async def get_iam_policy( maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -1208,14 +1188,14 @@ async def get_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified instance resource. @@ -1246,7 +1226,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1270,10 +1249,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py index 99cad77f03..248478dd80 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -36,10 +34,9 @@ from google.api_core import operation_async # type: ignore from google.cloud.spanner_admin_instance_v1.services.instance_admin import pagers from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore - +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 InstanceAdminTransport, DEFAULT_CLIENT_INFO from .transports.grpc import InstanceAdminGrpcTransport from .transports.grpc_asyncio import InstanceAdminGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class InstanceAdminClientMeta(type): _transport_registry["grpc_asyncio"] = InstanceAdminGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[InstanceAdminTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -102,7 +99,8 @@ class InstanceAdminClient(metaclass=InstanceAdminClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -136,7 +134,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -153,7 +152,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -172,36 +171,37 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstanceAdminTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstanceAdminTransport: The transport used by the client instance. + InstanceAdminTransport: The transport used by the client + instance. """ return self._transport @staticmethod def instance_path(project: str, instance: str,) -> str: - """Return a fully-qualified instance string.""" + """Returns a fully-qualified instance string.""" return "projects/{project}/instances/{instance}".format( project=project, instance=instance, ) @staticmethod def parse_instance_path(path: str) -> Dict[str, str]: - """Parse a instance path into its component segments.""" + """Parses a instance path into its component segments.""" m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def instance_config_path(project: str, instance_config: str,) -> str: - """Return a fully-qualified instance_config string.""" + """Returns a fully-qualified instance_config string.""" return "projects/{project}/instanceConfigs/{instance_config}".format( project=project, instance_config=instance_config, ) @staticmethod def parse_instance_config_path(path: str) -> Dict[str, str]: - """Parse a instance_config path into its component segments.""" + """Parses a instance_config path into its component segments.""" m = re.match( r"^projects/(?P.+?)/instanceConfigs/(?P.+?)$", path, @@ -210,7 +210,7 @@ def parse_instance_config_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -223,7 +223,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -245,7 +245,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -256,7 +256,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -270,12 +270,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstanceAdminTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instance admin client. + """Instantiates the instance admin client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -330,9 +330,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -344,12 +345,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -364,8 +367,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -404,7 +407,6 @@ def list_instance_configs( 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. @@ -436,10 +438,8 @@ def list_instance_configs( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.ListInstanceConfigsRequest): request = spanner_instance_admin.ListInstanceConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -489,7 +489,6 @@ def get_instance_config( 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. @@ -520,10 +519,8 @@ def get_instance_config( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.GetInstanceConfigRequest): request = spanner_instance_admin.GetInstanceConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -566,7 +563,6 @@ def list_instances( 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. @@ -598,10 +594,8 @@ def list_instances( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.ListInstancesRequest): request = spanner_instance_admin.ListInstancesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -649,7 +643,6 @@ def get_instance( 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. @@ -679,10 +672,8 @@ def get_instance( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.GetInstanceRequest): request = spanner_instance_admin.GetInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -779,7 +770,6 @@ def create_instance( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -812,10 +802,8 @@ def create_instance( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.CreateInstanceRequest): request = spanner_instance_admin.CreateInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if instance_id is not None: @@ -852,7 +840,7 @@ def update_instance( request: spanner_instance_admin.UpdateInstanceRequest = None, *, instance: spanner_instance_admin.Instance = None, - field_mask: gp_field_mask.FieldMask = None, + field_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -929,7 +917,6 @@ def update_instance( This corresponds to the ``field_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. @@ -962,10 +949,8 @@ def update_instance( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.UpdateInstanceRequest): request = spanner_instance_admin.UpdateInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if instance is not None: request.instance = instance if field_mask is not None: @@ -1030,7 +1015,6 @@ def delete_instance( 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. @@ -1053,10 +1037,8 @@ def delete_instance( # there are no flattened fields. if not isinstance(request, spanner_instance_admin.DeleteInstanceRequest): request = spanner_instance_admin.DeleteInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1077,13 +1059,13 @@ def delete_instance( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on an instance resource. Replaces any existing policy. @@ -1103,7 +1085,6 @@ def set_iam_policy( 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. @@ -1182,11 +1163,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1208,13 +1188,13 @@ def set_iam_policy( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. @@ -1235,7 +1215,6 @@ def get_iam_policy( 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. @@ -1314,11 +1293,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1340,14 +1318,14 @@ def get_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns permissions that the caller has on the specified instance resource. @@ -1378,7 +1356,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1402,14 +1379,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py index 1b9404231d..ba00792d47 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -249,7 +247,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py index b18f099ef8..cdcf8eb941 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py index e3b368c82a..5b6f2b655d 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,6 +41,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class InstanceAdminTransport(abc.ABC): """Abstract transport class for InstanceAdmin.""" @@ -51,21 +61,24 @@ class InstanceAdminTransport(abc.ABC): "https://www.googleapis.com/auth/spanner.admin", ) + DEFAULT_HOST: str = "spanner.googleapis.com" + def __init__( self, *, - host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -74,7 +87,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -88,29 +101,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -121,7 +181,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -135,7 +196,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -149,7 +211,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -163,7 +226,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -183,7 +247,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=3600.0, ), @@ -200,7 +265,8 @@ def _prep_wrapped_messages(self, client_info): maximum=32.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -222,11 +288,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.ListInstanceConfigsRequest], - typing.Union[ + Union[ spanner_instance_admin.ListInstanceConfigsResponse, - typing.Awaitable[spanner_instance_admin.ListInstanceConfigsResponse], + Awaitable[spanner_instance_admin.ListInstanceConfigsResponse], ], ]: raise NotImplementedError() @@ -234,11 +300,11 @@ def list_instance_configs( @property def get_instance_config( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.GetInstanceConfigRequest], - typing.Union[ + Union[ spanner_instance_admin.InstanceConfig, - typing.Awaitable[spanner_instance_admin.InstanceConfig], + Awaitable[spanner_instance_admin.InstanceConfig], ], ]: raise NotImplementedError() @@ -246,11 +312,11 @@ def get_instance_config( @property def list_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.ListInstancesRequest], - typing.Union[ + Union[ spanner_instance_admin.ListInstancesResponse, - typing.Awaitable[spanner_instance_admin.ListInstancesResponse], + Awaitable[spanner_instance_admin.ListInstancesResponse], ], ]: raise NotImplementedError() @@ -258,11 +324,10 @@ def list_instances( @property def get_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.GetInstanceRequest], - typing.Union[ - spanner_instance_admin.Instance, - typing.Awaitable[spanner_instance_admin.Instance], + Union[ + spanner_instance_admin.Instance, Awaitable[spanner_instance_admin.Instance] ], ]: raise NotImplementedError() @@ -270,56 +335,56 @@ def get_instance( @property def create_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.CreateInstanceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.UpdateInstanceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner_instance_admin.DeleteInstanceRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py index a3e3f39762..234d71e802 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import InstanceAdminTransport, DEFAULT_CLIENT_INFO @@ -75,7 +72,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -89,7 +86,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -200,7 +198,7 @@ def __init__( def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -231,13 +229,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -381,7 +381,9 @@ def get_instance( @property def create_instance( self, - ) -> Callable[[spanner_instance_admin.CreateInstanceRequest], operations.Operation]: + ) -> Callable[ + [spanner_instance_admin.CreateInstanceRequest], operations_pb2.Operation + ]: r"""Return a callable for the create instance method over gRPC. Creates an instance and begins preparing it to begin serving. @@ -437,14 +439,16 @@ def create_instance( self._stubs["create_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/CreateInstance", request_serializer=spanner_instance_admin.CreateInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_instance"] @property def update_instance( self, - ) -> Callable[[spanner_instance_admin.UpdateInstanceRequest], operations.Operation]: + ) -> Callable[ + [spanner_instance_admin.UpdateInstanceRequest], operations_pb2.Operation + ]: r"""Return a callable for the update instance method over gRPC. Updates an instance, and begins allocating or releasing @@ -507,14 +511,14 @@ def update_instance( self._stubs["update_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/UpdateInstance", request_serializer=spanner_instance_admin.UpdateInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_instance"] @property def delete_instance( self, - ) -> Callable[[spanner_instance_admin.DeleteInstanceRequest], empty.Empty]: + ) -> Callable[[spanner_instance_admin.DeleteInstanceRequest], empty_pb2.Empty]: r"""Return a callable for the delete instance method over gRPC. Deletes an instance. @@ -543,14 +547,14 @@ def delete_instance( self._stubs["delete_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/DeleteInstance", request_serializer=spanner_instance_admin.DeleteInstanceRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_instance"] @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> 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 on an instance resource. Replaces @@ -572,15 +576,15 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], policy.Policy]: + ) -> 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 an instance resource. Returns @@ -603,8 +607,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -612,7 +616,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -637,8 +642,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py index e4a860874e..a7e9acdc61 100644 --- a/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py +++ b/google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,26 +13,24 @@ # 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 +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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import InstanceAdminTransport, DEFAULT_CLIENT_INFO from .grpc import InstanceAdminGrpcTransport @@ -78,7 +75,7 @@ class InstanceAdminGrpcAsyncIOTransport(InstanceAdminTransport): def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -105,13 +102,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -119,7 +118,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -133,7 +132,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -192,7 +192,6 @@ def __init__( # 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 @@ -389,7 +388,8 @@ def get_instance( def create_instance( self, ) -> Callable[ - [spanner_instance_admin.CreateInstanceRequest], Awaitable[operations.Operation] + [spanner_instance_admin.CreateInstanceRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the create instance method over gRPC. @@ -446,7 +446,7 @@ def create_instance( self._stubs["create_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/CreateInstance", request_serializer=spanner_instance_admin.CreateInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_instance"] @@ -454,7 +454,8 @@ def create_instance( def update_instance( self, ) -> Callable[ - [spanner_instance_admin.UpdateInstanceRequest], Awaitable[operations.Operation] + [spanner_instance_admin.UpdateInstanceRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the update instance method over gRPC. @@ -518,7 +519,7 @@ def update_instance( self._stubs["update_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/UpdateInstance", request_serializer=spanner_instance_admin.UpdateInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_instance"] @@ -526,7 +527,7 @@ def update_instance( def delete_instance( self, ) -> Callable[ - [spanner_instance_admin.DeleteInstanceRequest], Awaitable[empty.Empty] + [spanner_instance_admin.DeleteInstanceRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete instance method over gRPC. @@ -556,14 +557,14 @@ def delete_instance( self._stubs["delete_instance"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/DeleteInstance", request_serializer=spanner_instance_admin.DeleteInstanceRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_instance"] @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 on an instance resource. Replaces @@ -585,15 +586,15 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + 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.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> 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 an instance resource. Returns @@ -616,8 +617,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -625,8 +626,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -651,8 +652,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.spanner.admin.instance.v1.InstanceAdmin/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/spanner_admin_instance_v1/types/__init__.py b/google/cloud/spanner_admin_instance_v1/types/__init__.py index f5ebcd7d5c..4833678c88 100644 --- a/google/cloud/spanner_admin_instance_v1/types/__init__.py +++ b/google/cloud/spanner_admin_instance_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .spanner_instance_admin import ( CreateInstanceMetadata, CreateInstanceRequest, diff --git a/google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py b/google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py index c5ffa63447..db885f8469 100644 --- a/google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py +++ b/google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # 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 as gp_field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,7 +42,6 @@ class ReplicaInfo(proto.Message): r""" - Attributes: location (str): The location of the serving resources, e.g. @@ -70,11 +66,9 @@ class ReplicaType(proto.Enum): READ_ONLY = 2 WITNESS = 3 - location = proto.Field(proto.STRING, number=1) - + location = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=ReplicaType,) - - default_leader_location = proto.Field(proto.BOOL, number=3) + default_leader_location = proto.Field(proto.BOOL, number=3,) class InstanceConfig(proto.Message): @@ -96,10 +90,8 @@ class InstanceConfig(proto.Message): properties. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) replicas = proto.RepeatedField(proto.MESSAGE, number=3, message="ReplicaInfo",) @@ -181,19 +173,13 @@ class State(proto.Enum): CREATING = 1 READY = 2 - name = proto.Field(proto.STRING, number=1) - - config = proto.Field(proto.STRING, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - node_count = proto.Field(proto.INT32, number=5) - + name = proto.Field(proto.STRING, number=1,) + config = proto.Field(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + node_count = proto.Field(proto.INT32, number=5,) state = proto.Field(proto.ENUM, number=6, enum=State,) - - labels = proto.MapField(proto.STRING, proto.STRING, number=7) - - endpoint_uris = proto.RepeatedField(proto.STRING, number=8) + labels = proto.MapField(proto.STRING, proto.STRING, number=7,) + endpoint_uris = proto.RepeatedField(proto.STRING, number=8,) class ListInstanceConfigsRequest(proto.Message): @@ -216,11 +202,9 @@ class ListInstanceConfigsRequest(proto.Message): [ListInstanceConfigsResponse][google.spanner.admin.instance.v1.ListInstanceConfigsResponse]. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListInstanceConfigsResponse(proto.Message): @@ -244,8 +228,7 @@ def raw_page(self): instance_configs = proto.RepeatedField( proto.MESSAGE, number=1, message="InstanceConfig", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetInstanceConfigRequest(proto.Message): @@ -259,7 +242,7 @@ class GetInstanceConfigRequest(proto.Message): ``projects//instanceConfigs/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetInstanceRequest(proto.Message): @@ -278,9 +261,8 @@ class GetInstanceRequest(proto.Message): are returned. """ - name = proto.Field(proto.STRING, number=1) - - field_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + name = proto.Field(proto.STRING, number=1,) + field_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,) class CreateInstanceRequest(proto.Message): @@ -301,10 +283,8 @@ class CreateInstanceRequest(proto.Message): ``/instances/``. """ - parent = proto.Field(proto.STRING, number=1) - - instance_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + instance_id = proto.Field(proto.STRING, number=2,) instance = proto.Field(proto.MESSAGE, number=3, message="Instance",) @@ -350,13 +330,10 @@ class ListInstancesRequest(proto.Message): containing "dev". """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListInstancesResponse(proto.Message): @@ -377,8 +354,7 @@ def raw_page(self): return self instances = proto.RepeatedField(proto.MESSAGE, number=1, message="Instance",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateInstanceRequest(proto.Message): @@ -402,8 +378,7 @@ class UpdateInstanceRequest(proto.Message): """ instance = proto.Field(proto.MESSAGE, number=1, message="Instance",) - - field_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + field_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,) class DeleteInstanceRequest(proto.Message): @@ -416,7 +391,7 @@ class DeleteInstanceRequest(proto.Message): of the form ``projects//instances/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateInstanceMetadata(proto.Message): @@ -441,12 +416,9 @@ class CreateInstanceMetadata(proto.Message): """ instance = proto.Field(proto.MESSAGE, number=1, message="Instance",) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - cancel_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + cancel_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) class UpdateInstanceMetadata(proto.Message): @@ -471,12 +443,9 @@ class UpdateInstanceMetadata(proto.Message): """ instance = proto.Field(proto.MESSAGE, number=1, message="Instance",) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - cancel_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + cancel_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_v1/__init__.py b/google/cloud/spanner_v1/__init__.py index a6e8b6b6bf..7c9e9d70fe 100644 --- a/google/cloud/spanner_v1/__init__.py +++ b/google/cloud/spanner_v1/__init__.py @@ -21,6 +21,7 @@ __version__ = pkg_resources.get_distribution("google-cloud-spanner").version from .services.spanner import SpannerClient +from .types.commit_response import CommitResponse from .types.keys import KeyRange as KeyRangePB from .types.keys import KeySet as KeySetPB from .types.mutation import Mutation @@ -34,7 +35,6 @@ from .types.spanner import BatchCreateSessionsResponse from .types.spanner import BeginTransactionRequest from .types.spanner import CommitRequest -from .types.spanner import CommitResponse from .types.spanner import CreateSessionRequest from .types.spanner import DeleteSessionRequest from .types.spanner import ExecuteBatchDmlRequest diff --git a/google/cloud/spanner_v1/gapic_metadata.json b/google/cloud/spanner_v1/gapic_metadata.json new file mode 100644 index 0000000000..a6b16725c3 --- /dev/null +++ b/google/cloud/spanner_v1/gapic_metadata.json @@ -0,0 +1,173 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.spanner_v1", + "protoPackage": "google.spanner.v1", + "schema": "1.0", + "services": { + "Spanner": { + "clients": { + "grpc": { + "libraryClient": "SpannerClient", + "rpcs": { + "BatchCreateSessions": { + "methods": [ + "batch_create_sessions" + ] + }, + "BeginTransaction": { + "methods": [ + "begin_transaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "CreateSession": { + "methods": [ + "create_session" + ] + }, + "DeleteSession": { + "methods": [ + "delete_session" + ] + }, + "ExecuteBatchDml": { + "methods": [ + "execute_batch_dml" + ] + }, + "ExecuteSql": { + "methods": [ + "execute_sql" + ] + }, + "ExecuteStreamingSql": { + "methods": [ + "execute_streaming_sql" + ] + }, + "GetSession": { + "methods": [ + "get_session" + ] + }, + "ListSessions": { + "methods": [ + "list_sessions" + ] + }, + "PartitionQuery": { + "methods": [ + "partition_query" + ] + }, + "PartitionRead": { + "methods": [ + "partition_read" + ] + }, + "Read": { + "methods": [ + "read" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "StreamingRead": { + "methods": [ + "streaming_read" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SpannerAsyncClient", + "rpcs": { + "BatchCreateSessions": { + "methods": [ + "batch_create_sessions" + ] + }, + "BeginTransaction": { + "methods": [ + "begin_transaction" + ] + }, + "Commit": { + "methods": [ + "commit" + ] + }, + "CreateSession": { + "methods": [ + "create_session" + ] + }, + "DeleteSession": { + "methods": [ + "delete_session" + ] + }, + "ExecuteBatchDml": { + "methods": [ + "execute_batch_dml" + ] + }, + "ExecuteSql": { + "methods": [ + "execute_sql" + ] + }, + "ExecuteStreamingSql": { + "methods": [ + "execute_streaming_sql" + ] + }, + "GetSession": { + "methods": [ + "get_session" + ] + }, + "ListSessions": { + "methods": [ + "list_sessions" + ] + }, + "PartitionQuery": { + "methods": [ + "partition_query" + ] + }, + "PartitionRead": { + "methods": [ + "partition_read" + ] + }, + "Read": { + "methods": [ + "read" + ] + }, + "Rollback": { + "methods": [ + "rollback" + ] + }, + "StreamingRead": { + "methods": [ + "streaming_read" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/spanner_v1/services/__init__.py b/google/cloud/spanner_v1/services/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/google/cloud/spanner_v1/services/__init__.py +++ b/google/cloud/spanner_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/spanner_v1/services/spanner/__init__.py b/google/cloud/spanner_v1/services/spanner/__init__.py index d00c69053d..53f14ea629 100644 --- a/google/cloud/spanner_v1/services/spanner/__init__.py +++ b/google/cloud/spanner_v1/services/spanner/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SpannerClient from .async_client import SpannerAsyncClient diff --git a/google/cloud/spanner_v1/services/spanner/async_client.py b/google/cloud/spanner_v1/services/spanner/async_client.py index d220c20f6e..6b8e199b8f 100644 --- a/google/cloud/spanner_v1/services/spanner/async_client.py +++ b/google/cloud/spanner_v1/services/spanner/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,21 +20,21 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.spanner_v1.services.spanner import pagers +from google.cloud.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import mutation from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import spanner from google.cloud.spanner_v1.types import transaction -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore - +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import SpannerTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SpannerGrpcAsyncIOTransport from .client import SpannerClient @@ -57,31 +55,27 @@ class SpannerAsyncClient: parse_database_path = staticmethod(SpannerClient.parse_database_path) session_path = staticmethod(SpannerClient.session_path) parse_session_path = staticmethod(SpannerClient.parse_session_path) - common_billing_account_path = staticmethod( SpannerClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SpannerClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SpannerClient.common_folder_path) parse_common_folder_path = staticmethod(SpannerClient.parse_common_folder_path) - common_organization_path = staticmethod(SpannerClient.common_organization_path) parse_common_organization_path = staticmethod( SpannerClient.parse_common_organization_path ) - common_project_path = staticmethod(SpannerClient.common_project_path) parse_common_project_path = staticmethod(SpannerClient.parse_common_project_path) - common_location_path = staticmethod(SpannerClient.common_location_path) parse_common_location_path = staticmethod(SpannerClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +90,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +107,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpannerTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SpannerTransport: The transport used by the client instance. @@ -127,12 +121,12 @@ def transport(self) -> SpannerTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SpannerTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the spanner client. + """Instantiates the spanner client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SpannerClient( credentials=credentials, transport=transport, @@ -212,7 +205,6 @@ async def create_session( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -237,7 +229,6 @@ async def create_session( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -249,7 +240,9 @@ async def create_session( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -306,7 +299,6 @@ async def batch_create_sessions( This corresponds to the ``session_count`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -333,7 +325,6 @@ async def batch_create_sessions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database if session_count is not None: @@ -347,7 +338,9 @@ async def batch_create_sessions( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -390,7 +383,6 @@ async def get_session( 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. @@ -415,7 +407,6 @@ async def get_session( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -427,7 +418,9 @@ async def get_session( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -468,7 +461,6 @@ async def list_sessions( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -498,7 +490,6 @@ async def list_sessions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -510,7 +501,9 @@ async def list_sessions( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=3600.0, ), default_timeout=3600.0, @@ -559,7 +552,6 @@ async def delete_session( 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. @@ -580,7 +572,6 @@ async def delete_session( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -592,7 +583,9 @@ async def delete_session( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -638,7 +631,6 @@ async def execute_sql( The request object. The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -652,7 +644,6 @@ async def execute_sql( """ # Create or coerce a protobuf request object. - request = spanner.ExecuteSqlRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -663,7 +654,9 @@ async def execute_sql( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -702,7 +695,6 @@ def execute_streaming_sql( The request object. The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -719,7 +711,6 @@ def execute_streaming_sql( """ # Create or coerce a protobuf request object. - request = spanner.ExecuteSqlRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -769,7 +760,6 @@ async def execute_batch_dml( request (:class:`google.cloud.spanner_v1.types.ExecuteBatchDmlRequest`): The request object. The request for [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -820,7 +810,6 @@ async def execute_batch_dml( """ # Create or coerce a protobuf request object. - request = spanner.ExecuteBatchDmlRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -831,7 +820,9 @@ async def execute_batch_dml( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -879,7 +870,6 @@ async def read( The request object. The request for [Read][google.spanner.v1.Spanner.Read] and [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -893,7 +883,6 @@ async def read( """ # Create or coerce a protobuf request object. - request = spanner.ReadRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -904,7 +893,9 @@ async def read( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -943,7 +934,6 @@ def streaming_read( The request object. The request for [Read][google.spanner.v1.Spanner.Read] and [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -960,7 +950,6 @@ def streaming_read( """ # Create or coerce a protobuf request object. - request = spanner.ReadRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1017,7 +1006,6 @@ async def begin_transaction( This corresponds to the ``options`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1042,7 +1030,6 @@ async def begin_transaction( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if options is not None: @@ -1056,7 +1043,9 @@ async def begin_transaction( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -1086,7 +1075,7 @@ async def commit( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> spanner.CommitResponse: + ) -> commit_response.CommitResponse: r"""Commits a transaction. The request includes the mutations to be applied to rows in the database. @@ -1146,7 +1135,6 @@ async def commit( This corresponds to the ``single_use_transaction`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1175,14 +1163,12 @@ async def commit( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if transaction_id is not None: request.transaction_id = transaction_id if single_use_transaction is not None: request.single_use_transaction = single_use_transaction - if mutations: request.mutations.extend(mutations) @@ -1194,7 +1180,9 @@ async def commit( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=3600.0, ), default_timeout=3600.0, @@ -1252,7 +1240,6 @@ async def rollback( This corresponds to the ``transaction_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. @@ -1273,7 +1260,6 @@ async def rollback( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if transaction_id is not None: @@ -1287,7 +1273,9 @@ async def rollback( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -1332,7 +1320,6 @@ async def partition_query( request (:class:`google.cloud.spanner_v1.types.PartitionQueryRequest`): The request object. The request for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1347,7 +1334,6 @@ async def partition_query( """ # Create or coerce a protobuf request object. - request = spanner.PartitionQueryRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1358,7 +1344,9 @@ async def partition_query( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -1407,7 +1395,6 @@ async def partition_read( request (:class:`google.cloud.spanner_v1.types.PartitionReadRequest`): The request object. The request for [PartitionRead][google.spanner.v1.Spanner.PartitionRead] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1422,7 +1409,6 @@ async def partition_read( """ # Create or coerce a protobuf request object. - request = spanner.PartitionReadRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1433,7 +1419,9 @@ async def partition_read( initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, diff --git a/google/cloud/spanner_v1/services/spanner/client.py b/google/cloud/spanner_v1/services/spanner/client.py index 387be03369..526dc5af73 100644 --- a/google/cloud/spanner_v1/services/spanner/client.py +++ b/google/cloud/spanner_v1/services/spanner/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,24 +21,24 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.spanner_v1.services.spanner import pagers +from google.cloud.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import mutation from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import spanner from google.cloud.spanner_v1.types import transaction -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore - +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import SpannerTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpannerGrpcTransport from .transports.grpc_asyncio import SpannerGrpcAsyncIOTransport @@ -59,7 +57,7 @@ class SpannerClientMeta(type): _transport_registry["grpc_asyncio"] = SpannerGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SpannerTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +83,8 @@ class SpannerClient(metaclass=SpannerClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -119,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +136,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,23 +155,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpannerTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SpannerTransport: The transport used by the client instance. + SpannerTransport: The transport used by the client + instance. """ return self._transport @staticmethod def database_path(project: str, instance: str, database: str,) -> str: - """Return a fully-qualified database string.""" + """Returns a fully-qualified database string.""" return "projects/{project}/instances/{instance}/databases/{database}".format( project=project, instance=instance, database=database, ) @staticmethod def parse_database_path(path: str) -> Dict[str, str]: - """Parse a database path into its component segments.""" + """Parses a database path into its component segments.""" m = re.match( r"^projects/(?P.+?)/instances/(?P.+?)/databases/(?P.+?)$", path, @@ -180,14 +181,14 @@ def parse_database_path(path: str) -> Dict[str, str]: @staticmethod def session_path(project: str, instance: str, database: str, session: str,) -> str: - """Return a fully-qualified session string.""" + """Returns a fully-qualified session string.""" return "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}".format( project=project, instance=instance, database=database, session=session, ) @staticmethod def parse_session_path(path: str) -> Dict[str, str]: - """Parse a session path into its component segments.""" + """Parses a session path into its component segments.""" m = re.match( r"^projects/(?P.+?)/instances/(?P.+?)/databases/(?P.+?)/sessions/(?P.+?)$", path, @@ -196,7 +197,7 @@ def parse_session_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -209,7 +210,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -220,7 +221,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -231,7 +232,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -242,7 +243,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -256,12 +257,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SpannerTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the spanner client. + """Instantiates the spanner client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -316,9 +317,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -330,12 +332,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -350,8 +354,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -406,7 +410,6 @@ def create_session( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -433,10 +436,8 @@ def create_session( # there are no flattened fields. if not isinstance(request, spanner.CreateSessionRequest): request = spanner.CreateSessionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -494,7 +495,6 @@ def batch_create_sessions( This corresponds to the ``session_count`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -523,10 +523,8 @@ def batch_create_sessions( # there are no flattened fields. if not isinstance(request, spanner.BatchCreateSessionsRequest): request = spanner.BatchCreateSessionsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database if session_count is not None: @@ -572,7 +570,6 @@ def get_session( 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. @@ -599,10 +596,8 @@ def get_session( # there are no flattened fields. if not isinstance(request, spanner.GetSessionRequest): request = spanner.GetSessionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -644,7 +639,6 @@ def list_sessions( This corresponds to the ``database`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -676,10 +670,8 @@ def list_sessions( # there are no flattened fields. if not isinstance(request, spanner.ListSessionsRequest): request = spanner.ListSessionsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if database is not None: request.database = database @@ -729,7 +721,6 @@ def delete_session( 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. @@ -752,10 +743,8 @@ def delete_session( # there are no flattened fields. if not isinstance(request, spanner.DeleteSessionRequest): request = spanner.DeleteSessionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -802,7 +791,6 @@ def execute_sql( The request object. The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -816,7 +804,6 @@ def execute_sql( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.ExecuteSqlRequest. # There's no risk of modifying the input as we've already verified @@ -860,7 +847,6 @@ def execute_streaming_sql( The request object. The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -877,7 +863,6 @@ def execute_streaming_sql( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.ExecuteSqlRequest. # There's no risk of modifying the input as we've already verified @@ -928,7 +913,6 @@ def execute_batch_dml( request (google.cloud.spanner_v1.types.ExecuteBatchDmlRequest): The request object. The request for [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -979,7 +963,6 @@ def execute_batch_dml( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.ExecuteBatchDmlRequest. # There's no risk of modifying the input as we've already verified @@ -1032,7 +1015,6 @@ def read( The request object. The request for [Read][google.spanner.v1.Spanner.Read] and [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1046,7 +1028,6 @@ def read( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.ReadRequest. # There's no risk of modifying the input as we've already verified @@ -1090,7 +1071,6 @@ def streaming_read( The request object. The request for [Read][google.spanner.v1.Spanner.Read] and [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1107,7 +1087,6 @@ def streaming_read( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.ReadRequest. # There's no risk of modifying the input as we've already verified @@ -1165,7 +1144,6 @@ def begin_transaction( This corresponds to the ``options`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1192,10 +1170,8 @@ def begin_transaction( # there are no flattened fields. if not isinstance(request, spanner.BeginTransactionRequest): request = spanner.BeginTransactionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if options is not None: @@ -1228,7 +1204,7 @@ def commit( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> spanner.CommitResponse: + ) -> commit_response.CommitResponse: r"""Commits a transaction. The request includes the mutations to be applied to rows in the database. @@ -1288,7 +1264,6 @@ def commit( This corresponds to the ``single_use_transaction`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1319,10 +1294,8 @@ def commit( # there are no flattened fields. if not isinstance(request, spanner.CommitRequest): request = spanner.CommitRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if transaction_id is not None: @@ -1387,7 +1360,6 @@ def rollback( This corresponds to the ``transaction_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. @@ -1410,10 +1382,8 @@ def rollback( # there are no flattened fields. if not isinstance(request, spanner.RollbackRequest): request = spanner.RollbackRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if transaction_id is not None: @@ -1461,7 +1431,6 @@ def partition_query( request (google.cloud.spanner_v1.types.PartitionQueryRequest): The request object. The request for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1476,7 +1445,6 @@ def partition_query( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.PartitionQueryRequest. # There's no risk of modifying the input as we've already verified @@ -1530,7 +1498,6 @@ def partition_read( request (google.cloud.spanner_v1.types.PartitionReadRequest): The request object. The request for [PartitionRead][google.spanner.v1.Spanner.PartitionRead] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1545,7 +1512,6 @@ def partition_read( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a spanner.PartitionReadRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/spanner_v1/services/spanner/pagers.py b/google/cloud/spanner_v1/services/spanner/pagers.py index e33003b4f5..4fea920f68 100644 --- a/google/cloud/spanner_v1/services/spanner/pagers.py +++ b/google/cloud/spanner_v1/services/spanner/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/spanner_v1/services/spanner/transports/__init__.py b/google/cloud/spanner_v1/services/spanner/transports/__init__.py index 2210e30dd8..189d62b427 100644 --- a/google/cloud/spanner_v1/services/spanner/transports/__init__.py +++ b/google/cloud/spanner_v1/services/spanner/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/spanner_v1/services/spanner/transports/base.py b/google/cloud/spanner_v1/services/spanner/transports/base.py index f91b98d6fb..b0fb6c3d63 100644 --- a/google/cloud/spanner_v1/services/spanner/transports/base.py +++ b/google/cloud/spanner_v1/services/spanner/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import spanner from google.cloud.spanner_v1.types import transaction -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SpannerTransport(abc.ABC): """Abstract transport class for Spanner.""" @@ -47,21 +58,24 @@ class SpannerTransport(abc.ABC): "https://www.googleapis.com/auth/spanner.data", ) + DEFAULT_HOST: str = "spanner.googleapis.com" + def __init__( self, *, - host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -70,7 +84,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -84,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +177,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -128,7 +191,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=60.0, ), default_timeout=60.0, @@ -140,7 +205,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -152,7 +219,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=3600.0, ), default_timeout=3600.0, @@ -164,7 +233,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -176,7 +247,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -193,7 +266,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -205,7 +280,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -220,7 +297,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -232,7 +311,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=3600.0, ), default_timeout=3600.0, @@ -244,7 +325,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -256,7 +339,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -268,7 +353,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.25, maximum=32.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=30.0, ), default_timeout=30.0, @@ -279,20 +366,20 @@ def _prep_wrapped_messages(self, client_info): @property def create_session( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.CreateSessionRequest], - typing.Union[spanner.Session, typing.Awaitable[spanner.Session]], + Union[spanner.Session, Awaitable[spanner.Session]], ]: raise NotImplementedError() @property def batch_create_sessions( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.BatchCreateSessionsRequest], - typing.Union[ + Union[ spanner.BatchCreateSessionsResponse, - typing.Awaitable[spanner.BatchCreateSessionsResponse], + Awaitable[spanner.BatchCreateSessionsResponse], ], ]: raise NotImplementedError() @@ -300,60 +387,54 @@ def batch_create_sessions( @property def get_session( self, - ) -> typing.Callable[ - [spanner.GetSessionRequest], - typing.Union[spanner.Session, typing.Awaitable[spanner.Session]], + ) -> Callable[ + [spanner.GetSessionRequest], Union[spanner.Session, Awaitable[spanner.Session]] ]: raise NotImplementedError() @property def list_sessions( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ListSessionsRequest], - typing.Union[ - spanner.ListSessionsResponse, typing.Awaitable[spanner.ListSessionsResponse] - ], + Union[spanner.ListSessionsResponse, Awaitable[spanner.ListSessionsResponse]], ]: raise NotImplementedError() @property def delete_session( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.DeleteSessionRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def execute_sql( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ExecuteSqlRequest], - typing.Union[result_set.ResultSet, typing.Awaitable[result_set.ResultSet]], + Union[result_set.ResultSet, Awaitable[result_set.ResultSet]], ]: raise NotImplementedError() @property def execute_streaming_sql( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ExecuteSqlRequest], - typing.Union[ - result_set.PartialResultSet, typing.Awaitable[result_set.PartialResultSet] - ], + Union[result_set.PartialResultSet, Awaitable[result_set.PartialResultSet]], ]: raise NotImplementedError() @property def execute_batch_dml( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ExecuteBatchDmlRequest], - typing.Union[ - spanner.ExecuteBatchDmlResponse, - typing.Awaitable[spanner.ExecuteBatchDmlResponse], + Union[ + spanner.ExecuteBatchDmlResponse, Awaitable[spanner.ExecuteBatchDmlResponse] ], ]: raise NotImplementedError() @@ -361,71 +442,64 @@ def execute_batch_dml( @property def read( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ReadRequest], - typing.Union[result_set.ResultSet, typing.Awaitable[result_set.ResultSet]], + Union[result_set.ResultSet, Awaitable[result_set.ResultSet]], ]: raise NotImplementedError() @property def streaming_read( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.ReadRequest], - typing.Union[ - result_set.PartialResultSet, typing.Awaitable[result_set.PartialResultSet] - ], + Union[result_set.PartialResultSet, Awaitable[result_set.PartialResultSet]], ]: raise NotImplementedError() @property def begin_transaction( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.BeginTransactionRequest], - typing.Union[ - transaction.Transaction, typing.Awaitable[transaction.Transaction] - ], + Union[transaction.Transaction, Awaitable[transaction.Transaction]], ]: raise NotImplementedError() @property def commit( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.CommitRequest], - typing.Union[spanner.CommitResponse, typing.Awaitable[spanner.CommitResponse]], + Union[ + commit_response.CommitResponse, Awaitable[commit_response.CommitResponse] + ], ]: raise NotImplementedError() @property def rollback( self, - ) -> typing.Callable[ - [spanner.RollbackRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [spanner.RollbackRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def partition_query( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.PartitionQueryRequest], - typing.Union[ - spanner.PartitionResponse, typing.Awaitable[spanner.PartitionResponse] - ], + Union[spanner.PartitionResponse, Awaitable[spanner.PartitionResponse]], ]: raise NotImplementedError() @property def partition_read( self, - ) -> typing.Callable[ + ) -> Callable[ [spanner.PartitionReadRequest], - typing.Union[ - spanner.PartitionResponse, typing.Awaitable[spanner.PartitionResponse] - ], + Union[spanner.PartitionResponse, Awaitable[spanner.PartitionResponse]], ]: raise NotImplementedError() diff --git a/google/cloud/spanner_v1/services/spanner/transports/grpc.py b/google/cloud/spanner_v1/services/spanner/transports/grpc.py index 0a3ead94e5..15e97c4446 100644 --- a/google/cloud/spanner_v1/services/spanner/transports/grpc.py +++ b/google/cloud/spanner_v1/services/spanner/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +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 -from google import auth # type: ignore -from google.auth import credentials # 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.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import spanner from google.cloud.spanner_v1.types import transaction -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SpannerTransport, DEFAULT_CLIENT_INFO @@ -55,7 +53,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -179,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -210,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -354,7 +355,9 @@ def list_sessions( return self._stubs["list_sessions"] @property - def delete_session(self) -> Callable[[spanner.DeleteSessionRequest], empty.Empty]: + def delete_session( + self, + ) -> Callable[[spanner.DeleteSessionRequest], empty_pb2.Empty]: r"""Return a callable for the delete session method over gRPC. Ends a session, releasing server resources associated @@ -375,7 +378,7 @@ def delete_session(self) -> Callable[[spanner.DeleteSessionRequest], empty.Empty self._stubs["delete_session"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/DeleteSession", request_serializer=spanner.DeleteSessionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session"] @@ -588,7 +591,9 @@ def begin_transaction( return self._stubs["begin_transaction"] @property - def commit(self) -> Callable[[spanner.CommitRequest], spanner.CommitResponse]: + def commit( + self, + ) -> Callable[[spanner.CommitRequest], commit_response.CommitResponse]: r"""Return a callable for the commit method over gRPC. Commits a transaction. The request includes the mutations to be @@ -622,12 +627,12 @@ def commit(self) -> Callable[[spanner.CommitRequest], spanner.CommitResponse]: self._stubs["commit"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/Commit", request_serializer=spanner.CommitRequest.serialize, - response_deserializer=spanner.CommitResponse.deserialize, + response_deserializer=commit_response.CommitResponse.deserialize, ) return self._stubs["commit"] @property - def rollback(self) -> Callable[[spanner.RollbackRequest], empty.Empty]: + def rollback(self) -> Callable[[spanner.RollbackRequest], empty_pb2.Empty]: r"""Return a callable for the rollback method over gRPC. Rolls back a transaction, releasing any locks it holds. It is a @@ -655,7 +660,7 @@ def rollback(self) -> Callable[[spanner.RollbackRequest], empty.Empty]: self._stubs["rollback"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/Rollback", request_serializer=spanner.RollbackRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["rollback"] diff --git a/google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py b/google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py index a7c83ef512..f87b4504de 100644 --- a/google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py +++ b/google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,23 @@ # 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 +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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore +from google.cloud.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import spanner from google.cloud.spanner_v1.types import transaction -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SpannerTransport, DEFAULT_CLIENT_INFO from .grpc import SpannerGrpcTransport @@ -58,7 +56,7 @@ class SpannerGrpcAsyncIOTransport(SpannerTransport): def create_channel( cls, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +99,7 @@ def __init__( self, *, host: str = "spanner.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -171,7 +172,6 @@ def __init__( # 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 @@ -365,7 +365,7 @@ def list_sessions( @property def delete_session( self, - ) -> Callable[[spanner.DeleteSessionRequest], Awaitable[empty.Empty]]: + ) -> Callable[[spanner.DeleteSessionRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete session method over gRPC. Ends a session, releasing server resources associated @@ -386,7 +386,7 @@ def delete_session( self._stubs["delete_session"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/DeleteSession", request_serializer=spanner.DeleteSessionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session"] @@ -605,7 +605,7 @@ def begin_transaction( @property def commit( self, - ) -> Callable[[spanner.CommitRequest], Awaitable[spanner.CommitResponse]]: + ) -> Callable[[spanner.CommitRequest], Awaitable[commit_response.CommitResponse]]: r"""Return a callable for the commit method over gRPC. Commits a transaction. The request includes the mutations to be @@ -639,12 +639,14 @@ def commit( self._stubs["commit"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/Commit", request_serializer=spanner.CommitRequest.serialize, - response_deserializer=spanner.CommitResponse.deserialize, + response_deserializer=commit_response.CommitResponse.deserialize, ) return self._stubs["commit"] @property - def rollback(self) -> Callable[[spanner.RollbackRequest], Awaitable[empty.Empty]]: + def rollback( + self, + ) -> Callable[[spanner.RollbackRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the rollback method over gRPC. Rolls back a transaction, releasing any locks it holds. It is a @@ -672,7 +674,7 @@ def rollback(self) -> Callable[[spanner.RollbackRequest], Awaitable[empty.Empty] self._stubs["rollback"] = self.grpc_channel.unary_unary( "/google.spanner.v1.Spanner/Rollback", request_serializer=spanner.RollbackRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["rollback"] diff --git a/google/cloud/spanner_v1/types/__init__.py b/google/cloud/spanner_v1/types/__init__.py index 7a7ac395e4..5f7bbfb8b1 100644 --- a/google/cloud/spanner_v1/types/__init__.py +++ b/google/cloud/spanner_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # - +from .commit_response import CommitResponse from .keys import ( KeyRange, KeySet, @@ -35,7 +34,6 @@ BatchCreateSessionsResponse, BeginTransactionRequest, CommitRequest, - CommitResponse, CreateSessionRequest, DeleteSessionRequest, ExecuteBatchDmlRequest, @@ -66,6 +64,7 @@ ) __all__ = ( + "CommitResponse", "KeyRange", "KeySet", "Mutation", @@ -79,7 +78,6 @@ "BatchCreateSessionsResponse", "BeginTransactionRequest", "CommitRequest", - "CommitResponse", "CreateSessionRequest", "DeleteSessionRequest", "ExecuteBatchDmlRequest", diff --git a/google/cloud/spanner_v1/types/commit_response.py b/google/cloud/spanner_v1/types/commit_response.py new file mode 100644 index 0000000000..1d20714bbd --- /dev/null +++ b/google/cloud/spanner_v1/types/commit_response.py @@ -0,0 +1,59 @@ +# -*- 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.spanner.v1", manifest={"CommitResponse",},) + + +class CommitResponse(proto.Message): + r"""The response for [Commit][google.spanner.v1.Spanner.Commit]. + Attributes: + commit_timestamp (google.protobuf.timestamp_pb2.Timestamp): + The Cloud Spanner timestamp at which the + transaction committed. + commit_stats (google.cloud.spanner_v1.types.CommitResponse.CommitStats): + The statistics about this Commit. Not returned by default. + For more information, see + [CommitRequest.return_commit_stats][google.spanner.v1.CommitRequest.return_commit_stats]. + """ + + class CommitStats(proto.Message): + r"""Additional statistics about a commit. + Attributes: + mutation_count (int): + The total number of mutations for the transaction. Knowing + the ``mutation_count`` value can help you maximize the + number of mutations in a transaction and minimize the number + of API round trips. You can also monitor this value to + prevent transactions from exceeding the system + `limit `__. + If the number of mutations exceeds the limit, the server + returns + `INVALID_ARGUMENT `__. + """ + + mutation_count = proto.Field(proto.INT64, number=1,) + + commit_timestamp = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, + ) + commit_stats = proto.Field(proto.MESSAGE, number=2, message=CommitStats,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_v1/types/keys.py b/google/cloud/spanner_v1/types/keys.py index fc5e20315b..7c4f094aa2 100644 --- a/google/cloud/spanner_v1/types/keys.py +++ b/google/cloud/spanner_v1/types/keys.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -157,19 +154,16 @@ class KeyRange(proto.Message): """ start_closed = proto.Field( - proto.MESSAGE, number=1, oneof="start_key_type", message=struct.ListValue, + proto.MESSAGE, number=1, oneof="start_key_type", message=struct_pb2.ListValue, ) - start_open = proto.Field( - proto.MESSAGE, number=2, oneof="start_key_type", message=struct.ListValue, + proto.MESSAGE, number=2, oneof="start_key_type", message=struct_pb2.ListValue, ) - end_closed = proto.Field( - proto.MESSAGE, number=3, oneof="end_key_type", message=struct.ListValue, + proto.MESSAGE, number=3, oneof="end_key_type", message=struct_pb2.ListValue, ) - end_open = proto.Field( - proto.MESSAGE, number=4, oneof="end_key_type", message=struct.ListValue, + proto.MESSAGE, number=4, oneof="end_key_type", message=struct_pb2.ListValue, ) @@ -200,11 +194,9 @@ class KeySet(proto.Message): only yielded once. """ - keys = proto.RepeatedField(proto.MESSAGE, number=1, message=struct.ListValue,) - + keys = proto.RepeatedField(proto.MESSAGE, number=1, message=struct_pb2.ListValue,) ranges = proto.RepeatedField(proto.MESSAGE, number=2, message="KeyRange",) - - all_ = proto.Field(proto.BOOL, number=3) + all_ = proto.Field(proto.BOOL, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_v1/types/mutation.py b/google/cloud/spanner_v1/types/mutation.py index f2204942be..632f77eaaf 100644 --- a/google/cloud/spanner_v1/types/mutation.py +++ b/google/cloud/spanner_v1/types/mutation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.spanner_v1.types import keys -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module(package="google.spanner.v1", manifest={"Mutation",},) @@ -102,15 +99,14 @@ class Write(proto.Message): [here][google.spanner.v1.TypeCode]. """ - table = proto.Field(proto.STRING, number=1) - - columns = proto.RepeatedField(proto.STRING, number=2) - - values = proto.RepeatedField(proto.MESSAGE, number=3, message=struct.ListValue,) + table = proto.Field(proto.STRING, number=1,) + columns = proto.RepeatedField(proto.STRING, number=2,) + values = proto.RepeatedField( + proto.MESSAGE, number=3, message=struct_pb2.ListValue, + ) class Delete(proto.Message): r"""Arguments to [delete][google.spanner.v1.Mutation.delete] operations. - Attributes: table (str): Required. The table whose rows will be @@ -125,20 +121,15 @@ class Delete(proto.Message): succeed even if some or all rows do not exist. """ - table = proto.Field(proto.STRING, number=1) - + table = proto.Field(proto.STRING, number=1,) key_set = proto.Field(proto.MESSAGE, number=2, message=keys.KeySet,) insert = proto.Field(proto.MESSAGE, number=1, oneof="operation", message=Write,) - update = proto.Field(proto.MESSAGE, number=2, oneof="operation", message=Write,) - insert_or_update = proto.Field( proto.MESSAGE, number=3, oneof="operation", message=Write, ) - replace = proto.Field(proto.MESSAGE, number=4, oneof="operation", message=Write,) - delete = proto.Field(proto.MESSAGE, number=5, oneof="operation", message=Delete,) diff --git a/google/cloud/spanner_v1/types/query_plan.py b/google/cloud/spanner_v1/types/query_plan.py index c3c3a536d6..27df7bc908 100644 --- a/google/cloud/spanner_v1/types/query_plan.py +++ b/google/cloud/spanner_v1/types/query_plan.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -104,11 +101,9 @@ class ChildLink(proto.Message): to the variable names assigned to the columns. """ - child_index = proto.Field(proto.INT32, number=1) - - type_ = proto.Field(proto.STRING, number=2) - - variable = proto.Field(proto.STRING, number=3) + child_index = proto.Field(proto.INT32, number=1,) + type_ = proto.Field(proto.STRING, number=2,) + variable = proto.Field(proto.STRING, number=3,) class ShortRepresentation(proto.Message): r"""Condensed representation of a node and its subtree. Only present for @@ -126,25 +121,18 @@ class ShortRepresentation(proto.Message): subquery may not necessarily be a direct child of this node. """ - description = proto.Field(proto.STRING, number=1) - - subqueries = proto.MapField(proto.STRING, proto.INT32, number=2) - - index = proto.Field(proto.INT32, number=1) + description = proto.Field(proto.STRING, number=1,) + subqueries = proto.MapField(proto.STRING, proto.INT32, number=2,) + index = proto.Field(proto.INT32, number=1,) kind = proto.Field(proto.ENUM, number=2, enum=Kind,) - - display_name = proto.Field(proto.STRING, number=3) - + display_name = proto.Field(proto.STRING, number=3,) child_links = proto.RepeatedField(proto.MESSAGE, number=4, message=ChildLink,) - short_representation = proto.Field( proto.MESSAGE, number=5, message=ShortRepresentation, ) - - metadata = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - - execution_stats = proto.Field(proto.MESSAGE, number=7, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=6, message=struct_pb2.Struct,) + execution_stats = proto.Field(proto.MESSAGE, number=7, message=struct_pb2.Struct,) class QueryPlan(proto.Message): diff --git a/google/cloud/spanner_v1/types/result_set.py b/google/cloud/spanner_v1/types/result_set.py index 9112ae63a0..2b2cad1451 100644 --- a/google/cloud/spanner_v1/types/result_set.py +++ b/google/cloud/spanner_v1/types/result_set.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.spanner_v1.types import query_plan as gs_query_plan from google.cloud.spanner_v1.types import transaction as gs_transaction from google.cloud.spanner_v1.types import type as gs_type -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -59,9 +56,7 @@ class ResultSet(proto.Message): """ metadata = proto.Field(proto.MESSAGE, number=1, message="ResultSetMetadata",) - - rows = proto.RepeatedField(proto.MESSAGE, number=2, message=struct.ListValue,) - + rows = proto.RepeatedField(proto.MESSAGE, number=2, message=struct_pb2.ListValue,) stats = proto.Field(proto.MESSAGE, number=3, message="ResultSetStats",) @@ -181,13 +176,9 @@ class PartialResultSet(proto.Message): """ metadata = proto.Field(proto.MESSAGE, number=1, message="ResultSetMetadata",) - - values = proto.RepeatedField(proto.MESSAGE, number=2, message=struct.Value,) - - chunked_value = proto.Field(proto.BOOL, number=3) - - resume_token = proto.Field(proto.BYTES, number=4) - + values = proto.RepeatedField(proto.MESSAGE, number=2, message=struct_pb2.Value,) + chunked_value = proto.Field(proto.BOOL, number=3,) + resume_token = proto.Field(proto.BYTES, number=4,) stats = proto.Field(proto.MESSAGE, number=5, message="ResultSetStats",) @@ -215,7 +206,6 @@ class ResultSetMetadata(proto.Message): """ row_type = proto.Field(proto.MESSAGE, number=1, message=gs_type.StructType,) - transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.Transaction, ) @@ -252,12 +242,9 @@ class ResultSetStats(proto.Message): """ query_plan = proto.Field(proto.MESSAGE, number=1, message=gs_query_plan.QueryPlan,) - - query_stats = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - row_count_exact = proto.Field(proto.INT64, number=3, oneof="row_count") - - row_count_lower_bound = proto.Field(proto.INT64, number=4, oneof="row_count") + query_stats = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + row_count_exact = proto.Field(proto.INT64, number=3, oneof="row_count",) + row_count_lower_bound = proto.Field(proto.INT64, number=4, oneof="row_count",) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_v1/types/spanner.py b/google/cloud/spanner_v1/types/spanner.py index acb32c8ff9..bbfd28af92 100644 --- a/google/cloud/spanner_v1/types/spanner.py +++ b/google/cloud/spanner_v1/types/spanner.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,18 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.spanner_v1.types import keys from google.cloud.spanner_v1.types import mutation from google.cloud.spanner_v1.types import result_set from google.cloud.spanner_v1.types import transaction as gs_transaction from google.cloud.spanner_v1.types import type as gs_type -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -51,7 +48,6 @@ "ReadRequest", "BeginTransactionRequest", "CommitRequest", - "CommitResponse", "RollbackRequest", }, ) @@ -69,8 +65,7 @@ class CreateSessionRequest(proto.Message): The session to create. """ - database = proto.Field(proto.STRING, number=1) - + database = proto.Field(proto.STRING, number=1,) session = proto.Field(proto.MESSAGE, number=2, message="Session",) @@ -95,11 +90,9 @@ class BatchCreateSessionsRequest(proto.Message): as necessary). """ - database = proto.Field(proto.STRING, number=1) - + database = proto.Field(proto.STRING, number=1,) session_template = proto.Field(proto.MESSAGE, number=2, message="Session",) - - session_count = proto.Field(proto.INT32, number=3) + session_count = proto.Field(proto.INT32, number=3,) class BatchCreateSessionsResponse(proto.Message): @@ -116,7 +109,6 @@ class BatchCreateSessionsResponse(proto.Message): class Session(proto.Message): r"""A session in the Cloud Spanner API. - Attributes: name (str): Output only. The name of the session. This is @@ -144,27 +136,23 @@ class Session(proto.Message): earlier than the actual last use time. """ - name = proto.Field(proto.STRING, number=1) - - labels = proto.MapField(proto.STRING, proto.STRING, number=2) - - create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + labels = proto.MapField(proto.STRING, proto.STRING, number=2,) + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) approximate_last_use_time = proto.Field( - proto.MESSAGE, number=4, message=timestamp.Timestamp, + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, ) class GetSessionRequest(proto.Message): r"""The request for [GetSession][google.spanner.v1.Spanner.GetSession]. - Attributes: name (str): Required. The name of the session to retrieve. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListSessionsRequest(proto.Message): @@ -198,13 +186,10 @@ class ListSessionsRequest(proto.Message): and the value of the label contains the string "dev". """ - database = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + database = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListSessionsResponse(proto.Message): @@ -225,8 +210,7 @@ def raw_page(self): return self sessions = proto.RepeatedField(proto.MESSAGE, number=1, message="Session",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class DeleteSessionRequest(proto.Message): @@ -238,12 +222,11 @@ class DeleteSessionRequest(proto.Message): Required. The name of the session to delete. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class RequestOptions(proto.Message): r"""Common request options for various APIs. - Attributes: priority (google.cloud.spanner_v1.types.RequestOptions.Priority): Priority for the request. @@ -252,10 +235,11 @@ class RequestOptions(proto.Message): used for statistics collection. Both request_tag and transaction_tag can be specified for a read or query that belongs to a transaction. This field is ignored for requests - where it's not applicable (e.g. CommitRequest). - ``request_tag`` must be a valid identifier of the form: - ``[a-zA-Z][a-zA-Z0-9_\-]`` between 2 and 64 characters in - length + where it's not applicable (e.g. CommitRequest). Legal + characters for ``request_tag`` values are all printable + characters (ASCII 32 - 126) and the length of a request_tag + is limited to 50 characters. Values that exceed this limit + are truncated. transaction_tag (str): A tag used for statistics collection about this transaction. Both request_tag and transaction_tag can be specified for a @@ -263,8 +247,10 @@ class RequestOptions(proto.Message): transaction_tag should be the same for all requests belonging to the same transaction. If this request doesn’t belong to any transaction, transaction_tag will be ignored. - ``transaction_tag`` must be a valid identifier of the - format: ``[a-zA-Z][a-zA-Z0-9_\-]{0,49}`` + Legal characters for ``transaction_tag`` values are all + printable characters (ASCII 32 - 126) and the length of a + transaction_tag is limited to 50 characters. Values that + exceed this limit are truncated. """ class Priority(proto.Enum): @@ -292,10 +278,8 @@ class Priority(proto.Enum): PRIORITY_HIGH = 3 priority = proto.Field(proto.ENUM, number=1, enum=Priority,) - - request_tag = proto.Field(proto.STRING, number=2) - - transaction_tag = proto.Field(proto.STRING, number=3) + request_tag = proto.Field(proto.STRING, number=2,) + transaction_tag = proto.Field(proto.STRING, number=3,) class ExecuteSqlRequest(proto.Message): @@ -405,7 +389,6 @@ class QueryMode(proto.Enum): class QueryOptions(proto.Message): r"""Query optimizer configuration. - Attributes: optimizer_version (str): An option to control the selection of optimizer version. @@ -461,34 +444,23 @@ class QueryOptions(proto.Message): garbage collection fails with an ``INVALID_ARGUMENT`` error. """ - optimizer_version = proto.Field(proto.STRING, number=1) - - optimizer_statistics_package = proto.Field(proto.STRING, number=2) - - session = proto.Field(proto.STRING, number=1) + optimizer_version = proto.Field(proto.STRING, number=1,) + optimizer_statistics_package = proto.Field(proto.STRING, number=2,) + session = proto.Field(proto.STRING, number=1,) transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionSelector, ) - - sql = proto.Field(proto.STRING, number=3) - - params = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + sql = proto.Field(proto.STRING, number=3,) + params = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) param_types = proto.MapField( proto.STRING, proto.MESSAGE, number=5, message=gs_type.Type, ) - - resume_token = proto.Field(proto.BYTES, number=6) - + resume_token = proto.Field(proto.BYTES, number=6,) query_mode = proto.Field(proto.ENUM, number=7, enum=QueryMode,) - - partition_token = proto.Field(proto.BYTES, number=8) - - seqno = proto.Field(proto.INT64, number=9) - + partition_token = proto.Field(proto.BYTES, number=8,) + seqno = proto.Field(proto.INT64, number=9,) query_options = proto.Field(proto.MESSAGE, number=10, message=QueryOptions,) - request_options = proto.Field(proto.MESSAGE, number=11, message="RequestOptions",) @@ -535,7 +507,6 @@ class ExecuteBatchDmlRequest(proto.Message): class Statement(proto.Message): r"""A single DML statement. - Attributes: sql (str): Required. The DML string. @@ -570,24 +541,18 @@ class Statement(proto.Message): SQL types. """ - sql = proto.Field(proto.STRING, number=1) - - params = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - + sql = proto.Field(proto.STRING, number=1,) + params = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) param_types = proto.MapField( proto.STRING, proto.MESSAGE, number=3, message=gs_type.Type, ) - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionSelector, ) - statements = proto.RepeatedField(proto.MESSAGE, number=3, message=Statement,) - - seqno = proto.Field(proto.INT64, number=4) - + seqno = proto.Field(proto.INT64, number=4,) request_options = proto.Field(proto.MESSAGE, number=5, message="RequestOptions",) @@ -649,8 +614,7 @@ class ExecuteBatchDmlResponse(proto.Message): result_sets = proto.RepeatedField( proto.MESSAGE, number=1, message=result_set.ResultSet, ) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) class PartitionOptions(proto.Message): @@ -678,9 +642,8 @@ class PartitionOptions(proto.Message): this maximum count request. """ - partition_size_bytes = proto.Field(proto.INT64, number=1) - - max_partitions = proto.Field(proto.INT64, number=2) + partition_size_bytes = proto.Field(proto.INT64, number=1,) + max_partitions = proto.Field(proto.INT64, number=2,) class PartitionQueryRequest(proto.Message): @@ -742,20 +705,15 @@ class PartitionQueryRequest(proto.Message): partitions are created. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionSelector, ) - - sql = proto.Field(proto.STRING, number=3) - - params = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + sql = proto.Field(proto.STRING, number=3,) + params = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) param_types = proto.MapField( proto.STRING, proto.MESSAGE, number=5, message=gs_type.Type, ) - partition_options = proto.Field( proto.MESSAGE, number=6, message="PartitionOptions", ) @@ -810,20 +768,14 @@ class PartitionReadRequest(proto.Message): partitions are created. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionSelector, ) - - table = proto.Field(proto.STRING, number=3) - - index = proto.Field(proto.STRING, number=4) - - columns = proto.RepeatedField(proto.STRING, number=5) - + table = proto.Field(proto.STRING, number=3,) + index = proto.Field(proto.STRING, number=4,) + columns = proto.RepeatedField(proto.STRING, number=5,) key_set = proto.Field(proto.MESSAGE, number=6, message=keys.KeySet,) - partition_options = proto.Field( proto.MESSAGE, number=9, message="PartitionOptions", ) @@ -842,7 +794,7 @@ class Partition(proto.Message): token. """ - partition_token = proto.Field(proto.BYTES, number=1) + partition_token = proto.Field(proto.BYTES, number=1,) class PartitionResponse(proto.Message): @@ -858,7 +810,6 @@ class PartitionResponse(proto.Message): """ partitions = proto.RepeatedField(proto.MESSAGE, number=1, message="Partition",) - transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.Transaction, ) @@ -938,26 +889,17 @@ class ReadRequest(proto.Message): Common options for this request. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) transaction = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionSelector, ) - - table = proto.Field(proto.STRING, number=3) - - index = proto.Field(proto.STRING, number=4) - - columns = proto.RepeatedField(proto.STRING, number=5) - + table = proto.Field(proto.STRING, number=3,) + index = proto.Field(proto.STRING, number=4,) + columns = proto.RepeatedField(proto.STRING, number=5,) key_set = proto.Field(proto.MESSAGE, number=6, message=keys.KeySet,) - - limit = proto.Field(proto.INT64, number=8) - - resume_token = proto.Field(proto.BYTES, number=9) - - partition_token = proto.Field(proto.BYTES, number=10) - + limit = proto.Field(proto.INT64, number=8,) + resume_token = proto.Field(proto.BYTES, number=9,) + partition_token = proto.Field(proto.BYTES, number=10,) request_options = proto.Field(proto.MESSAGE, number=11, message="RequestOptions",) @@ -979,18 +921,15 @@ class BeginTransactionRequest(proto.Message): this transaction instead. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) options = proto.Field( proto.MESSAGE, number=2, message=gs_transaction.TransactionOptions, ) - request_options = proto.Field(proto.MESSAGE, number=3, message="RequestOptions",) class CommitRequest(proto.Message): r"""The request for [Commit][google.spanner.v1.Spanner.Commit]. - Attributes: session (str): Required. The session in which the @@ -1021,65 +960,21 @@ class CommitRequest(proto.Message): Common options for this request. """ - session = proto.Field(proto.STRING, number=1) - - transaction_id = proto.Field(proto.BYTES, number=2, oneof="transaction") - + session = proto.Field(proto.STRING, number=1,) + transaction_id = proto.Field(proto.BYTES, number=2, oneof="transaction",) single_use_transaction = proto.Field( proto.MESSAGE, number=3, oneof="transaction", message=gs_transaction.TransactionOptions, ) - mutations = proto.RepeatedField(proto.MESSAGE, number=4, message=mutation.Mutation,) - - return_commit_stats = proto.Field(proto.BOOL, number=5) - + return_commit_stats = proto.Field(proto.BOOL, number=5,) request_options = proto.Field(proto.MESSAGE, number=6, message="RequestOptions",) -class CommitResponse(proto.Message): - r"""The response for [Commit][google.spanner.v1.Spanner.Commit]. - - Attributes: - commit_timestamp (google.protobuf.timestamp_pb2.Timestamp): - The Cloud Spanner timestamp at which the - transaction committed. - commit_stats (google.cloud.spanner_v1.types.CommitResponse.CommitStats): - The statistics about this Commit. Not returned by default. - For more information, see - [CommitRequest.return_commit_stats][google.spanner.v1.CommitRequest.return_commit_stats]. - """ - - class CommitStats(proto.Message): - r"""Additional statistics about a commit. - - Attributes: - mutation_count (int): - The total number of mutations for the transaction. Knowing - the ``mutation_count`` value can help you maximize the - number of mutations in a transaction and minimize the number - of API round trips. You can also monitor this value to - prevent transactions from exceeding the system - `limit `__. - If the number of mutations exceeds the limit, the server - returns - `INVALID_ARGUMENT `__. - """ - - mutation_count = proto.Field(proto.INT64, number=1) - - commit_timestamp = proto.Field( - proto.MESSAGE, number=1, message=timestamp.Timestamp, - ) - - commit_stats = proto.Field(proto.MESSAGE, number=2, message=CommitStats,) - - class RollbackRequest(proto.Message): r"""The request for [Rollback][google.spanner.v1.Spanner.Rollback]. - Attributes: session (str): Required. The session in which the @@ -1088,9 +983,8 @@ class RollbackRequest(proto.Message): Required. The transaction to roll back. """ - session = proto.Field(proto.STRING, number=1) - - transaction_id = proto.Field(proto.BYTES, number=2) + session = proto.Field(proto.STRING, number=1,) + transaction_id = proto.Field(proto.BYTES, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/spanner_v1/types/transaction.py b/google/cloud/spanner_v1/types/transaction.py index e20c6ad7b4..42c71f65d1 100644 --- a/google/cloud/spanner_v1/types/transaction.py +++ b/google/cloud/spanner_v1/types/transaction.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -29,9 +26,282 @@ class TransactionOptions(proto.Message): - r"""TransactionOptions are used to specify different types of transactions. - - For more info, see: https://cloud.google.com/spanner/docs/reference/rest/v1/Transaction + r"""Transactions: + Each session can have at most one active transaction at a time (note + that standalone reads and queries use a transaction internally and + do count towards the one transaction limit). After the active + transaction is completed, the session can immediately be re-used for + the next transaction. It is not necessary to create a new session + for each transaction. + + Transaction Modes: + Cloud Spanner supports three transaction modes: + + 1. Locking read-write. This type of transaction is the only way to + write data into Cloud Spanner. These transactions rely on + pessimistic locking and, if necessary, two-phase commit. Locking + read-write transactions may abort, requiring the application to + retry. + + 2. Snapshot read-only. This transaction type provides guaranteed + consistency across several reads, but does not allow writes. + Snapshot read-only transactions can be configured to read at + timestamps in the past. Snapshot read-only transactions do not + need to be committed. + + 3. Partitioned DML. This type of transaction is used to execute a + single Partitioned DML statement. Partitioned DML partitions the + key space and runs the DML statement over each partition in + parallel using separate, internal transactions that commit + independently. Partitioned DML transactions do not need to be + committed. + + For transactions that only read, snapshot read-only transactions + provide simpler semantics and are almost always faster. In + particular, read-only transactions do not take locks, so they do not + conflict with read-write transactions. As a consequence of not + taking locks, they also do not abort, so retry loops are not needed. + + Transactions may only read/write data in a single database. They + may, however, read/write data in different tables within that + database. + + Locking Read-Write Transactions: + Locking transactions may be used to atomically read-modify-write + data anywhere in a database. This type of transaction is externally + consistent. + + Clients should attempt to minimize the amount of time a transaction + is active. Faster transactions commit with higher probability and + cause less contention. Cloud Spanner attempts to keep read locks + active as long as the transaction continues to do reads, and the + transaction has not been terminated by + [Commit][google.spanner.v1.Spanner.Commit] or + [Rollback][google.spanner.v1.Spanner.Rollback]. Long periods of + inactivity at the client may cause Cloud Spanner to release a + transaction's locks and abort it. + + Conceptually, a read-write transaction consists of zero or more + reads or SQL statements followed by + [Commit][google.spanner.v1.Spanner.Commit]. At any time before + [Commit][google.spanner.v1.Spanner.Commit], the client can send a + [Rollback][google.spanner.v1.Spanner.Rollback] request to abort the + transaction. + + Semantics: + Cloud Spanner can commit the transaction if all read locks it + acquired are still valid at commit time, and it is able to acquire + write locks for all writes. Cloud Spanner can abort the transaction + for any reason. If a commit attempt returns ``ABORTED``, Cloud + Spanner guarantees that the transaction has not modified any user + data in Cloud Spanner. + + Unless the transaction commits, Cloud Spanner makes no guarantees + about how long the transaction's locks were held for. It is an error + to use Cloud Spanner locks for any sort of mutual exclusion other + than between Cloud Spanner transactions themselves. + + Retrying Aborted Transactions: + When a transaction aborts, the application can choose to retry the + whole transaction again. To maximize the chances of successfully + committing the retry, the client should execute the retry in the + same session as the original attempt. The original session's lock + priority increases with each consecutive abort, meaning that each + attempt has a slightly better chance of success than the previous. + + Under some circumstances (e.g., many transactions attempting to + modify the same row(s)), a transaction can abort many times in a + short period before successfully committing. Thus, it is not a good + idea to cap the number of retries a transaction can attempt; + instead, it is better to limit the total amount of wall time spent + retrying. + + Idle Transactions: + A transaction is considered idle if it has no outstanding reads or + SQL queries and has not started a read or SQL query within the last + 10 seconds. Idle transactions can be aborted by Cloud Spanner so + that they don't hold on to locks indefinitely. In that case, the + commit will fail with error ``ABORTED``. + + If this behavior is undesirable, periodically executing a simple SQL + query in the transaction (e.g., ``SELECT 1``) prevents the + transaction from becoming idle. + + Snapshot Read-Only Transactions: + Snapshot read-only transactions provides a simpler method than + locking read-write transactions for doing several consistent reads. + However, this type of transaction does not support writes. + + Snapshot transactions do not take locks. Instead, they work by + choosing a Cloud Spanner timestamp, then executing all reads at that + timestamp. Since they do not acquire locks, they do not block + concurrent read-write transactions. + + Unlike locking read-write transactions, snapshot read-only + transactions never abort. They can fail if the chosen read timestamp + is garbage collected; however, the default garbage collection policy + is generous enough that most applications do not need to worry about + this in practice. + + Snapshot read-only transactions do not need to call + [Commit][google.spanner.v1.Spanner.Commit] or + [Rollback][google.spanner.v1.Spanner.Rollback] (and in fact are not + permitted to do so). + + To execute a snapshot transaction, the client specifies a timestamp + bound, which tells Cloud Spanner how to choose a read timestamp. + + The types of timestamp bound are: + + - Strong (the default). + - Bounded staleness. + - Exact staleness. + + If the Cloud Spanner database to be read is geographically + distributed, stale read-only transactions can execute more quickly + than strong or read-write transaction, because they are able to + execute far from the leader replica. + + Each type of timestamp bound is discussed in detail below. + + Strong: + Strong reads are guaranteed to see the effects of all transactions + that have committed before the start of the read. Furthermore, all + rows yielded by a single read are consistent with each other -- if + any part of the read observes a transaction, all parts of the read + see the transaction. + + Strong reads are not repeatable: two consecutive strong read-only + transactions might return inconsistent results if there are + concurrent writes. If consistency across reads is required, the + reads should be executed within a transaction or at an exact read + timestamp. + + See + [TransactionOptions.ReadOnly.strong][google.spanner.v1.TransactionOptions.ReadOnly.strong]. + + Exact Staleness: + These timestamp bounds execute reads at a user-specified timestamp. + Reads at a timestamp are guaranteed to see a consistent prefix of + the global transaction history: they observe modifications done by + all transactions with a commit timestamp <= the read timestamp, and + observe none of the modifications done by transactions with a larger + commit timestamp. They will block until all conflicting transactions + that may be assigned commit timestamps <= the read timestamp have + finished. + + The timestamp can either be expressed as an absolute Cloud Spanner + commit timestamp or a staleness relative to the current time. + + These modes do not require a "negotiation phase" to pick a + timestamp. As a result, they execute slightly faster than the + equivalent boundedly stale concurrency modes. On the other hand, + boundedly stale reads usually return fresher results. + + See + [TransactionOptions.ReadOnly.read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.read_timestamp] + and + [TransactionOptions.ReadOnly.exact_staleness][google.spanner.v1.TransactionOptions.ReadOnly.exact_staleness]. + + Bounded Staleness: + Bounded staleness modes allow Cloud Spanner to pick the read + timestamp, subject to a user-provided staleness bound. Cloud Spanner + chooses the newest timestamp within the staleness bound that allows + execution of the reads at the closest available replica without + blocking. + + All rows yielded are consistent with each other -- if any part of + the read observes a transaction, all parts of the read see the + transaction. Boundedly stale reads are not repeatable: two stale + reads, even if they use the same staleness bound, can execute at + different timestamps and thus return inconsistent results. + + Boundedly stale reads execute in two phases: the first phase + negotiates a timestamp among all replicas needed to serve the read. + In the second phase, reads are executed at the negotiated timestamp. + + As a result of the two phase execution, bounded staleness reads are + usually a little slower than comparable exact staleness reads. + However, they are typically able to return fresher results, and are + more likely to execute at the closest replica. + + Because the timestamp negotiation requires up-front knowledge of + which rows will be read, it can only be used with single-use + read-only transactions. + + See + [TransactionOptions.ReadOnly.max_staleness][google.spanner.v1.TransactionOptions.ReadOnly.max_staleness] + and + [TransactionOptions.ReadOnly.min_read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.min_read_timestamp]. + + Old Read Timestamps and Garbage Collection: + Cloud Spanner continuously garbage collects deleted and overwritten + data in the background to reclaim storage space. This process is + known as "version GC". By default, version GC reclaims versions + after they are one hour old. Because of this, Cloud Spanner cannot + perform reads at read timestamps more than one hour in the past. + This restriction also applies to in-progress reads and/or SQL + queries whose timestamp become too old while executing. Reads and + SQL queries with too-old read timestamps fail with the error + ``FAILED_PRECONDITION``. + + Partitioned DML Transactions: + Partitioned DML transactions are used to execute DML statements with + a different execution strategy that provides different, and often + better, scalability properties for large, table-wide operations than + DML in a ReadWrite transaction. Smaller scoped statements, such as + an OLTP workload, should prefer using ReadWrite transactions. + + Partitioned DML partitions the keyspace and runs the DML statement + on each partition in separate, internal transactions. These + transactions commit automatically when complete, and run + independently from one another. + + To reduce lock contention, this execution strategy only acquires + read locks on rows that match the WHERE clause of the statement. + Additionally, the smaller per-partition transactions hold locks for + less time. + + That said, Partitioned DML is not a drop-in replacement for standard + DML used in ReadWrite transactions. + + - The DML statement must be fully-partitionable. Specifically, the + statement must be expressible as the union of many statements + which each access only a single row of the table. + + - The statement is not applied atomically to all rows of the table. + Rather, the statement is applied atomically to partitions of the + table, in independent transactions. Secondary index rows are + updated atomically with the base table rows. + + - Partitioned DML does not guarantee exactly-once execution + semantics against a partition. The statement will be applied at + least once to each partition. It is strongly recommended that the + DML statement should be idempotent to avoid unexpected results. + For instance, it is potentially dangerous to run a statement such + as ``UPDATE table SET column = column + 1`` as it could be run + multiple times against some rows. + + - The partitions are committed automatically - there is no support + for Commit or Rollback. If the call returns an error, or if the + client issuing the ExecuteSql call dies, it is possible that some + rows had the statement executed on them successfully. It is also + possible that statement was never executed against other rows. + + - Partitioned DML transactions may only contain the execution of a + single DML statement via ExecuteSql or ExecuteStreamingSql. + + - If any error is encountered during the execution of the + partitioned DML operation (for instance, a UNIQUE INDEX + violation, division by zero, or a value that cannot be stored due + to schema constraints), then the operation is stopped at that + point and an error is returned. It is possible that at this + point, some partitions have been committed (or even committed + multiple times), and other partitions have not been run at all. + + Given the above, Partitioned DML is good fit for large, + database-wide, operations that are idempotent, such as deleting old + rows from a very large table. Attributes: read_write (google.cloud.spanner_v1.types.TransactionOptions.ReadWrite): @@ -58,10 +328,10 @@ class TransactionOptions(proto.Message): class ReadWrite(proto.Message): r"""Message type to initiate a read-write transaction. Currently this transaction type has no options. - """ + """ class PartitionedDml(proto.Message): - r"""Message type to initiate a Partitioned DML transaction.""" + r"""Message type to initiate a Partitioned DML transaction. """ class ReadOnly(proto.Message): r"""Message type to initiate a read-only transaction. @@ -130,38 +400,37 @@ class ReadOnly(proto.Message): message that describes the transaction. """ - strong = proto.Field(proto.BOOL, number=1, oneof="timestamp_bound") - + strong = proto.Field(proto.BOOL, number=1, oneof="timestamp_bound",) min_read_timestamp = proto.Field( proto.MESSAGE, number=2, oneof="timestamp_bound", - message=timestamp.Timestamp, + message=timestamp_pb2.Timestamp, ) - max_staleness = proto.Field( - proto.MESSAGE, number=3, oneof="timestamp_bound", message=duration.Duration, + proto.MESSAGE, + number=3, + oneof="timestamp_bound", + message=duration_pb2.Duration, ) - read_timestamp = proto.Field( proto.MESSAGE, number=4, oneof="timestamp_bound", - message=timestamp.Timestamp, + message=timestamp_pb2.Timestamp, ) - exact_staleness = proto.Field( - proto.MESSAGE, number=5, oneof="timestamp_bound", message=duration.Duration, + proto.MESSAGE, + number=5, + oneof="timestamp_bound", + message=duration_pb2.Duration, ) - - return_read_timestamp = proto.Field(proto.BOOL, number=6) + return_read_timestamp = proto.Field(proto.BOOL, number=6,) read_write = proto.Field(proto.MESSAGE, number=1, oneof="mode", message=ReadWrite,) - partitioned_dml = proto.Field( proto.MESSAGE, number=3, oneof="mode", message=PartitionedDml, ) - read_only = proto.Field(proto.MESSAGE, number=2, oneof="mode", message=ReadOnly,) @@ -187,9 +456,10 @@ class Transaction(proto.Message): nanoseconds. Example: ``"2014-10-02T15:01:23.045123456Z"``. """ - id = proto.Field(proto.BYTES, number=1) - - read_timestamp = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + id = proto.Field(proto.BYTES, number=1,) + read_timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, + ) class TransactionSelector(proto.Message): @@ -220,9 +490,7 @@ class TransactionSelector(proto.Message): single_use = proto.Field( proto.MESSAGE, number=1, oneof="selector", message="TransactionOptions", ) - - id = proto.Field(proto.BYTES, number=2, oneof="selector") - + id = proto.Field(proto.BYTES, number=2, oneof="selector",) begin = proto.Field( proto.MESSAGE, number=3, oneof="selector", message="TransactionOptions", ) diff --git a/google/cloud/spanner_v1/types/type.py b/google/cloud/spanner_v1/types/type.py index 0fd8d2f6a4..e06e5fc5b0 100644 --- a/google/cloud/spanner_v1/types/type.py +++ b/google/cloud/spanner_v1/types/type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -65,9 +63,7 @@ class Type(proto.Message): """ code = proto.Field(proto.ENUM, number=1, enum="TypeCode",) - array_element_type = proto.Field(proto.MESSAGE, number=2, message="Type",) - struct_type = proto.Field(proto.MESSAGE, number=3, message="StructType",) @@ -89,7 +85,6 @@ class StructType(proto.Message): class Field(proto.Message): r"""Message representing a single field of a struct. - Attributes: name (str): The name of the field. For reads, this is the column name. @@ -103,8 +98,7 @@ class Field(proto.Message): The type of the field. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.MESSAGE, number=2, message="Type",) fields = proto.RepeatedField(proto.MESSAGE, number=1, message=Field,) diff --git a/noxfile.py b/noxfile.py index 7f6991818e..efc4f53738 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,7 +62,7 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): """Run black. diff --git a/owlbot.py b/owlbot.py index e26186583d..0899ba8d90 100644 --- a/owlbot.py +++ b/owlbot.py @@ -13,27 +13,96 @@ # limitations under the License. """This script is used to synthesize generated parts of this library.""" + +from pathlib import Path +from typing import List, Optional + import synthtool as s from synthtool import gcp from synthtool.languages import python common = gcp.CommonTemplates() +# This is a customized version of the s.get_staging_dirs() function from synthtool to +# cater for copying 3 different folders from googleapis-gen +# which are spanner, spanner/admin/instance and spanner/admin/database. +# Source https://github.com/googleapis/synthtool/blob/master/synthtool/transforms.py#L280 +def get_staging_dirs( + default_version: Optional[str] = None, sub_directory: Optional[str] = None +) -> List[Path]: + """Returns the list of directories, one per version, copied from + https://github.com/googleapis/googleapis-gen. Will return in lexical sorting + order with the exception of the default_version which will be last (if specified). + + Args: + default_version (str): the default version of the API. The directory for this version + will be the last item in the returned list if specified. + sub_directory (str): if a `sub_directory` is provided, only the directories within the + specified `sub_directory` will be returned. + + Returns: the empty list if no file were copied. + """ + + staging = Path("owl-bot-staging") + + if sub_directory: + staging /= sub_directory + + if staging.is_dir(): + # Collect the subdirectories of the staging directory. + versions = [v.name for v in staging.iterdir() if v.is_dir()] + # Reorder the versions so the default version always comes last. + versions = [v for v in versions if v != default_version] + versions.sort() + if default_version is not None: + versions += [default_version] + dirs = [staging / v for v in versions] + for dir in dirs: + s._tracked_paths.add(dir) + return dirs + else: + return [] + spanner_default_version = "v1" spanner_admin_instance_default_version = "v1" spanner_admin_database_default_version = "v1" -for library in s.get_staging_dirs(spanner_default_version): - if library.parent.absolute() == "spanner": - s.move(library, excludes=["google/cloud/spanner/**", "*.*", "docs/index.rst", "google/cloud/spanner_v1/__init__.py"]) +for library in get_staging_dirs(spanner_default_version, "spanner"): + # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 + s.replace(library / f"google/cloud/spanner_{library.name}/types/transaction.py", + r""". + Attributes:""", + r""".\n + Attributes:""", + ) + + # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 + s.replace(library / f"google/cloud/spanner_{library.name}/types/transaction.py", + r""". + Attributes:""", + r""".\n + Attributes:""", + ) + + # Remove headings from docstring. Requested change upstream in cl/377290854 due to https://google.aip.dev/192#formatting. + s.replace(library / f"google/cloud/spanner_{library.name}/types/transaction.py", + """\n ==.*?==\n""", + ":", + ) + + # Remove headings from docstring. Requested change upstream in cl/377290854 due to https://google.aip.dev/192#formatting. + s.replace(library / f"google/cloud/spanner_{library.name}/types/transaction.py", + """\n --.*?--\n""", + ":", + ) + + s.move(library, excludes=["google/cloud/spanner/**", "*.*", "docs/index.rst", "google/cloud/spanner_v1/__init__.py"]) -for library in s.get_staging_dirs(spanner_admin_instance_default_version): - if library.parent.absolute() == "spanner_admin_instance": - s.move(library, excludes=["google/cloud/spanner_admin_instance/**", "*.*", "docs/index.rst"]) +for library in get_staging_dirs(spanner_admin_instance_default_version, "spanner_admin_instance"): + s.move(library, excludes=["google/cloud/spanner_admin_instance/**", "*.*", "docs/index.rst"]) -for library in s.get_staging_dirs(spanner_admin_database_default_version): - if library.parent.absolute() == "spanner_admin_database": - s.move(library, excludes=["google/cloud/spanner_admin_database/**", "*.*", "docs/index.rst"]) +for library in get_staging_dirs(spanner_admin_database_default_version, "spanner_admin_database"): + s.move(library, excludes=["google/cloud/spanner_admin_database/**", "*.*", "docs/index.rst"]) s.remove_staging_dirs() diff --git a/samples/samples/noxfile.py b/samples/samples/noxfile.py index 956cdf4f92..5ff9e1db58 100644 --- a/samples/samples/noxfile.py +++ b/samples/samples/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,6 +173,9 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): if os.path.exists("constraints.txt"): diff --git a/scripts/fixup_spanner_admin_database_v1_keywords.py b/scripts/fixup_spanner_admin_database_v1_keywords.py index 7eb3062dce..8a04d60b67 100644 --- a/scripts/fixup_spanner_admin_database_v1_keywords.py +++ b/scripts/fixup_spanner_admin_database_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,24 +39,23 @@ def partition( class spanner_admin_databaseCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_backup': ('parent', 'backup_id', 'backup', 'encryption_config', ), - 'create_database': ('parent', 'create_statement', 'extra_statements', 'encryption_config', ), - 'delete_backup': ('name', ), - 'drop_database': ('database', ), - 'get_backup': ('name', ), - 'get_database': ('name', ), - 'get_database_ddl': ('database', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_backup_operations': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_backups': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_database_operations': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_databases': ('parent', 'page_size', 'page_token', ), - 'restore_database': ('parent', 'database_id', 'backup', 'encryption_config', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_backup': ('backup', 'update_mask', ), - 'update_database_ddl': ('database', 'statements', 'operation_id', ), - + 'create_backup': ('parent', 'backup_id', 'backup', 'encryption_config', ), + 'create_database': ('parent', 'create_statement', 'extra_statements', 'encryption_config', ), + 'delete_backup': ('name', ), + 'drop_database': ('database', ), + 'get_backup': ('name', ), + 'get_database': ('name', ), + 'get_database_ddl': ('database', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_backup_operations': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_backups': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_database_operations': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_databases': ('parent', 'page_size', 'page_token', ), + 'restore_database': ('parent', 'database_id', 'backup', 'encryption_config', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_backup': ('backup', 'update_mask', ), + 'update_database_ddl': ('database', 'statements', 'operation_id', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -89,7 +86,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/scripts/fixup_spanner_admin_instance_v1_keywords.py b/scripts/fixup_spanner_admin_instance_v1_keywords.py index eb5507ec97..f52d1c5fe3 100644 --- a/scripts/fixup_spanner_admin_instance_v1_keywords.py +++ b/scripts/fixup_spanner_admin_instance_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,17 +39,16 @@ def partition( class spanner_admin_instanceCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_instance': ('parent', 'instance_id', 'instance', ), - 'delete_instance': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_instance': ('name', 'field_mask', ), - 'get_instance_config': ('name', ), - 'list_instance_configs': ('parent', 'page_size', 'page_token', ), - 'list_instances': ('parent', 'page_size', 'page_token', 'filter', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_instance': ('instance', 'field_mask', ), - + 'create_instance': ('parent', 'instance_id', 'instance', ), + 'delete_instance': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_instance': ('name', 'field_mask', ), + 'get_instance_config': ('name', ), + 'list_instance_configs': ('parent', 'page_size', 'page_token', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_instance': ('instance', 'field_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -82,7 +79,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/scripts/fixup_spanner_v1_keywords.py b/scripts/fixup_spanner_v1_keywords.py index 4faf734dcb..bff8352aa8 100644 --- a/scripts/fixup_spanner_v1_keywords.py +++ b/scripts/fixup_spanner_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,22 +39,21 @@ def partition( class spannerCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_sessions': ('database', 'session_count', 'session_template', ), - 'begin_transaction': ('session', 'options', 'request_options', ), - 'commit': ('session', 'transaction_id', 'single_use_transaction', 'mutations', 'return_commit_stats', 'request_options', ), - 'create_session': ('database', 'session', ), - 'delete_session': ('name', ), - 'execute_batch_dml': ('session', 'transaction', 'statements', 'seqno', 'request_options', ), - 'execute_sql': ('session', 'sql', 'transaction', 'params', 'param_types', 'resume_token', 'query_mode', 'partition_token', 'seqno', 'query_options', 'request_options', ), - 'execute_streaming_sql': ('session', 'sql', 'transaction', 'params', 'param_types', 'resume_token', 'query_mode', 'partition_token', 'seqno', 'query_options', 'request_options', ), - 'get_session': ('name', ), - 'list_sessions': ('database', 'page_size', 'page_token', 'filter', ), - 'partition_query': ('session', 'sql', 'transaction', 'params', 'param_types', 'partition_options', ), - 'partition_read': ('session', 'table', 'key_set', 'transaction', 'index', 'columns', 'partition_options', ), - 'read': ('session', 'table', 'columns', 'key_set', 'transaction', 'index', 'limit', 'resume_token', 'partition_token', 'request_options', ), - 'rollback': ('session', 'transaction_id', ), - 'streaming_read': ('session', 'table', 'columns', 'key_set', 'transaction', 'index', 'limit', 'resume_token', 'partition_token', 'request_options', ), - + 'batch_create_sessions': ('database', 'session_count', 'session_template', ), + 'begin_transaction': ('session', 'options', 'request_options', ), + 'commit': ('session', 'transaction_id', 'single_use_transaction', 'mutations', 'return_commit_stats', 'request_options', ), + 'create_session': ('database', 'session', ), + 'delete_session': ('name', ), + 'execute_batch_dml': ('session', 'transaction', 'statements', 'seqno', 'request_options', ), + 'execute_sql': ('session', 'sql', 'transaction', 'params', 'param_types', 'resume_token', 'query_mode', 'partition_token', 'seqno', 'query_options', 'request_options', ), + 'execute_streaming_sql': ('session', 'sql', 'transaction', 'params', 'param_types', 'resume_token', 'query_mode', 'partition_token', 'seqno', 'query_options', 'request_options', ), + 'get_session': ('name', ), + 'list_sessions': ('database', 'page_size', 'page_token', 'filter', ), + 'partition_query': ('session', 'sql', 'transaction', 'params', 'param_types', 'partition_options', ), + 'partition_read': ('session', 'table', 'key_set', 'transaction', 'index', 'columns', 'partition_options', ), + 'read': ('session', 'table', 'columns', 'key_set', 'transaction', 'index', 'limit', 'resume_token', 'partition_token', 'request_options', ), + 'rollback': ('session', 'transaction_id', ), + 'streaming_read': ('session', 'table', 'columns', 'key_set', 'transaction', 'index', 'limit', 'resume_token', 'partition_token', 'request_options', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -87,7 +84,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/tests/__init__.py b/tests/__init__.py index e69de29bb2..4de65971c2 100644 --- a/tests/__init__.py +++ b/tests/__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/tests/unit/__init__.py b/tests/unit/__init__.py index df379f1e9d..4de65971c2 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -1,4 +1,5 @@ -# Copyright 2016 Google LLC +# -*- 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. @@ -11,3 +12,4 @@ # WITHOUT 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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 0000000000..4de65971c2 --- /dev/null +++ b/tests/unit/gapic/__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/tests/unit/gapic/spanner_admin_database_v1/__init__.py b/tests/unit/gapic/spanner_admin_database_v1/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/tests/unit/gapic/spanner_admin_database_v1/__init__.py +++ b/tests/unit/gapic/spanner_admin_database_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/spanner_admin_database_v1/test_database_admin.py b/tests/unit/gapic/spanner_admin_database_v1/test_database_admin.py index 1906328473..28269154e0 100644 --- a/tests/unit/gapic/spanner_admin_database_v1/test_database_admin.py +++ b/tests/unit/gapic/spanner_admin_database_v1/test_database_admin.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.spanner_admin_database_v1.services.database_admin import ( DatabaseAdminAsyncClient, @@ -43,21 +42,51 @@ ) from google.cloud.spanner_admin_database_v1.services.database_admin import pagers from google.cloud.spanner_admin_database_v1.services.database_admin import transports +from google.cloud.spanner_admin_database_v1.services.database_admin.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.spanner_admin_database_v1.services.database_admin.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.spanner_admin_database_v1.types import backup from google.cloud.spanner_admin_database_v1.types import backup as gsad_backup from google.cloud.spanner_admin_database_v1.types import common from google.cloud.spanner_admin_database_v1.types import spanner_database_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 as operations # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -108,7 +137,7 @@ def test__get_default_mtls_endpoint(): "client_class", [DatabaseAdminClient, DatabaseAdminAsyncClient,] ) def test_database_admin_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -125,7 +154,7 @@ def test_database_admin_client_from_service_account_info(client_class): "client_class", [DatabaseAdminClient, DatabaseAdminAsyncClient,] ) def test_database_admin_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -178,7 +207,7 @@ def test_database_admin_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(DatabaseAdminClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -466,7 +495,7 @@ def test_list_databases( transport: str = "grpc", request_type=spanner_database_admin.ListDatabasesRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -479,19 +508,15 @@ def test_list_databases( call.return_value = spanner_database_admin.ListDatabasesResponse( next_page_token="next_page_token_value", ) - response = client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatabasesPager) - assert response.next_page_token == "next_page_token_value" @@ -503,7 +528,7 @@ def test_list_databases_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -511,7 +536,6 @@ def test_list_databases_empty_call(): client.list_databases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabasesRequest() @@ -521,7 +545,7 @@ async def test_list_databases_async( request_type=spanner_database_admin.ListDatabasesRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -536,18 +560,15 @@ async def test_list_databases_async( next_page_token="next_page_token_value", ) ) - response = await client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDatabasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -557,17 +578,17 @@ async def test_list_databases_async_from_dict(): def test_list_databases_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.ListDatabasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_databases), "__call__") as call: call.return_value = spanner_database_admin.ListDatabasesResponse() - client.list_databases(request) # Establish that the underlying gRPC stub method was called. @@ -582,11 +603,14 @@ def test_list_databases_field_headers(): @pytest.mark.asyncio async def test_list_databases_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.ListDatabasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -594,7 +618,6 @@ async def test_list_databases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_database_admin.ListDatabasesResponse() ) - await client.list_databases(request) # Establish that the underlying gRPC stub method was called. @@ -608,13 +631,12 @@ async def test_list_databases_field_headers_async(): def test_list_databases_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_databases), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner_database_admin.ListDatabasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_databases(parent="parent_value",) @@ -623,12 +645,11 @@ def test_list_databases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_databases_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -640,7 +661,9 @@ def test_list_databases_flattened_error(): @pytest.mark.asyncio async def test_list_databases_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_databases), "__call__") as call: @@ -658,13 +681,14 @@ async def test_list_databases_flattened_async(): # 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_databases_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -675,7 +699,7 @@ async def test_list_databases_flattened_error_async(): def test_list_databases_pager(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_databases), "__call__") as call: @@ -718,7 +742,7 @@ def test_list_databases_pager(): def test_list_databases_pages(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_databases), "__call__") as call: @@ -753,7 +777,7 @@ def test_list_databases_pages(): @pytest.mark.asyncio async def test_list_databases_async_pager(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -795,7 +819,7 @@ async def test_list_databases_async_pager(): @pytest.mark.asyncio async def test_list_databases_async_pages(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -836,7 +860,7 @@ def test_create_database( transport: str = "grpc", request_type=spanner_database_admin.CreateDatabaseRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -847,13 +871,11 @@ def test_create_database( with mock.patch.object(type(client.transport.create_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.CreateDatabaseRequest() # Establish that the response is the type that we expect. @@ -868,7 +890,7 @@ def test_create_database_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -876,7 +898,6 @@ def test_create_database_empty_call(): client.create_database() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.CreateDatabaseRequest() @@ -886,7 +907,7 @@ async def test_create_database_async( request_type=spanner_database_admin.CreateDatabaseRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -899,13 +920,11 @@ async def test_create_database_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.CreateDatabaseRequest() # Establish that the response is the type that we expect. @@ -918,17 +937,17 @@ async def test_create_database_async_from_dict(): def test_create_database_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.CreateDatabaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_database), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_database(request) # Establish that the underlying gRPC stub method was called. @@ -943,11 +962,14 @@ def test_create_database_field_headers(): @pytest.mark.asyncio async def test_create_database_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.CreateDatabaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -955,7 +977,6 @@ async def test_create_database_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_database(request) # Establish that the underlying gRPC stub method was called. @@ -969,13 +990,12 @@ async def test_create_database_field_headers_async(): def test_create_database_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_database( @@ -986,14 +1006,12 @@ def test_create_database_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].create_statement == "create_statement_value" def test_create_database_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1007,7 +1025,9 @@ def test_create_database_flattened_error(): @pytest.mark.asyncio async def test_create_database_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_database), "__call__") as call: @@ -1027,15 +1047,15 @@ async def test_create_database_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].create_statement == "create_statement_value" @pytest.mark.asyncio async def test_create_database_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1051,7 +1071,7 @@ def test_get_database( transport: str = "grpc", request_type=spanner_database_admin.GetDatabaseRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1066,23 +1086,17 @@ def test_get_database( state=spanner_database_admin.Database.State.CREATING, version_retention_period="version_retention_period_value", ) - response = client.get_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner_database_admin.Database) - assert response.name == "name_value" - assert response.state == spanner_database_admin.Database.State.CREATING - assert response.version_retention_period == "version_retention_period_value" @@ -1094,7 +1108,7 @@ def test_get_database_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1102,7 +1116,6 @@ def test_get_database_empty_call(): client.get_database() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseRequest() @@ -1112,7 +1125,7 @@ async def test_get_database_async( request_type=spanner_database_admin.GetDatabaseRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1129,22 +1142,17 @@ async def test_get_database_async( version_retention_period="version_retention_period_value", ) ) - response = await client.get_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner_database_admin.Database) - assert response.name == "name_value" - assert response.state == spanner_database_admin.Database.State.CREATING - assert response.version_retention_period == "version_retention_period_value" @@ -1154,17 +1162,17 @@ async def test_get_database_async_from_dict(): def test_get_database_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.GetDatabaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database), "__call__") as call: call.return_value = spanner_database_admin.Database() - client.get_database(request) # Establish that the underlying gRPC stub method was called. @@ -1179,11 +1187,14 @@ def test_get_database_field_headers(): @pytest.mark.asyncio async def test_get_database_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.GetDatabaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1191,7 +1202,6 @@ async def test_get_database_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_database_admin.Database() ) - await client.get_database(request) # Establish that the underlying gRPC stub method was called. @@ -1205,13 +1215,12 @@ async def test_get_database_field_headers_async(): def test_get_database_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner_database_admin.Database() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_database(name="name_value",) @@ -1220,12 +1229,11 @@ def test_get_database_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_database_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1237,7 +1245,9 @@ def test_get_database_flattened_error(): @pytest.mark.asyncio async def test_get_database_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database), "__call__") as call: @@ -1255,13 +1265,14 @@ async def test_get_database_flattened_async(): # 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_database_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1276,7 +1287,7 @@ def test_update_database_ddl( request_type=spanner_database_admin.UpdateDatabaseDdlRequest, ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1289,13 +1300,11 @@ def test_update_database_ddl( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_database_ddl(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.UpdateDatabaseDdlRequest() # Establish that the response is the type that we expect. @@ -1310,7 +1319,7 @@ def test_update_database_ddl_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1320,7 +1329,6 @@ def test_update_database_ddl_empty_call(): client.update_database_ddl() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.UpdateDatabaseDdlRequest() @@ -1330,7 +1338,7 @@ async def test_update_database_ddl_async( request_type=spanner_database_admin.UpdateDatabaseDdlRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1345,13 +1353,11 @@ async def test_update_database_ddl_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_database_ddl(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.UpdateDatabaseDdlRequest() # Establish that the response is the type that we expect. @@ -1364,11 +1370,12 @@ async def test_update_database_ddl_async_from_dict(): def test_update_database_ddl_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.UpdateDatabaseDdlRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1376,7 +1383,6 @@ def test_update_database_ddl_field_headers(): type(client.transport.update_database_ddl), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_database_ddl(request) # Establish that the underlying gRPC stub method was called. @@ -1391,11 +1397,14 @@ def test_update_database_ddl_field_headers(): @pytest.mark.asyncio async def test_update_database_ddl_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.UpdateDatabaseDdlRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1405,7 +1414,6 @@ async def test_update_database_ddl_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_database_ddl(request) # Establish that the underlying gRPC stub method was called. @@ -1419,7 +1427,7 @@ async def test_update_database_ddl_field_headers_async(): def test_update_database_ddl_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1427,7 +1435,6 @@ def test_update_database_ddl_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_database_ddl( @@ -1438,14 +1445,12 @@ def test_update_database_ddl_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" - assert args[0].statements == ["statements_value"] def test_update_database_ddl_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1459,7 +1464,9 @@ def test_update_database_ddl_flattened_error(): @pytest.mark.asyncio async def test_update_database_ddl_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1481,15 +1488,15 @@ async def test_update_database_ddl_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" - assert args[0].statements == ["statements_value"] @pytest.mark.asyncio async def test_update_database_ddl_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1505,7 +1512,7 @@ def test_drop_database( transport: str = "grpc", request_type=spanner_database_admin.DropDatabaseRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1516,13 +1523,11 @@ def test_drop_database( with mock.patch.object(type(client.transport.drop_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.drop_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.DropDatabaseRequest() # Establish that the response is the type that we expect. @@ -1537,7 +1542,7 @@ def test_drop_database_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1545,7 +1550,6 @@ def test_drop_database_empty_call(): client.drop_database() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.DropDatabaseRequest() @@ -1555,7 +1559,7 @@ async def test_drop_database_async( request_type=spanner_database_admin.DropDatabaseRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1566,13 +1570,11 @@ async def test_drop_database_async( with mock.patch.object(type(client.transport.drop_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.drop_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.DropDatabaseRequest() # Establish that the response is the type that we expect. @@ -1585,17 +1587,17 @@ async def test_drop_database_async_from_dict(): def test_drop_database_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.DropDatabaseRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.drop_database), "__call__") as call: call.return_value = None - client.drop_database(request) # Establish that the underlying gRPC stub method was called. @@ -1610,17 +1612,19 @@ def test_drop_database_field_headers(): @pytest.mark.asyncio async def test_drop_database_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.DropDatabaseRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.drop_database), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.drop_database(request) # Establish that the underlying gRPC stub method was called. @@ -1634,13 +1638,12 @@ async def test_drop_database_field_headers_async(): def test_drop_database_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.drop_database), "__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.drop_database(database="database_value",) @@ -1649,12 +1652,11 @@ def test_drop_database_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" def test_drop_database_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1666,7 +1668,9 @@ def test_drop_database_flattened_error(): @pytest.mark.asyncio async def test_drop_database_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.drop_database), "__call__") as call: @@ -1682,13 +1686,14 @@ async def test_drop_database_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" @pytest.mark.asyncio async def test_drop_database_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1702,7 +1707,7 @@ def test_get_database_ddl( transport: str = "grpc", request_type=spanner_database_admin.GetDatabaseDdlRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1715,19 +1720,15 @@ def test_get_database_ddl( call.return_value = spanner_database_admin.GetDatabaseDdlResponse( statements=["statements_value"], ) - response = client.get_database_ddl(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseDdlRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner_database_admin.GetDatabaseDdlResponse) - assert response.statements == ["statements_value"] @@ -1739,7 +1740,7 @@ def test_get_database_ddl_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1747,7 +1748,6 @@ def test_get_database_ddl_empty_call(): client.get_database_ddl() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseDdlRequest() @@ -1757,7 +1757,7 @@ async def test_get_database_ddl_async( request_type=spanner_database_admin.GetDatabaseDdlRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1772,18 +1772,15 @@ async def test_get_database_ddl_async( statements=["statements_value"], ) ) - response = await client.get_database_ddl(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.GetDatabaseDdlRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner_database_admin.GetDatabaseDdlResponse) - assert response.statements == ["statements_value"] @@ -1793,17 +1790,17 @@ async def test_get_database_ddl_async_from_dict(): def test_get_database_ddl_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.GetDatabaseDdlRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database_ddl), "__call__") as call: call.return_value = spanner_database_admin.GetDatabaseDdlResponse() - client.get_database_ddl(request) # Establish that the underlying gRPC stub method was called. @@ -1818,11 +1815,14 @@ def test_get_database_ddl_field_headers(): @pytest.mark.asyncio async def test_get_database_ddl_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.GetDatabaseDdlRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1830,7 +1830,6 @@ async def test_get_database_ddl_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_database_admin.GetDatabaseDdlResponse() ) - await client.get_database_ddl(request) # Establish that the underlying gRPC stub method was called. @@ -1844,13 +1843,12 @@ async def test_get_database_ddl_field_headers_async(): def test_get_database_ddl_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database_ddl), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner_database_admin.GetDatabaseDdlResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_database_ddl(database="database_value",) @@ -1859,12 +1857,11 @@ def test_get_database_ddl_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" def test_get_database_ddl_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1876,7 +1873,9 @@ def test_get_database_ddl_flattened_error(): @pytest.mark.asyncio async def test_get_database_ddl_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_database_ddl), "__call__") as call: @@ -1894,13 +1893,14 @@ async def test_get_database_ddl_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" @pytest.mark.asyncio async def test_get_database_ddl_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1911,10 +1911,10 @@ async def test_get_database_ddl_flattened_error_async(): def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1924,22 +1924,17 @@ def test_set_iam_policy( # 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.Policy(version=774, etag=b"etag_blob",) - + 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.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1951,7 +1946,7 @@ 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 = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1959,16 +1954,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + 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.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1979,22 +1973,18 @@ async def test_set_iam_policy_async( 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.Policy(version=774, etag=b"etag_blob",) + 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.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2004,17 +1994,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.SetIamPolicyRequest() + 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.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2029,17 +2019,19 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.SetIamPolicyRequest() + 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.Policy()) - + 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. @@ -2053,29 +2045,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.Policy() - + 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",) @@ -2084,31 +2074,32 @@ def test_set_iam_policy_flattened(): # 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 = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=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.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + 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.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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",) @@ -2117,27 +2108,28 @@ async def test_set_iam_policy_flattened_async(): # 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 = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_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.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2147,22 +2139,17 @@ def test_get_iam_policy( # 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.Policy(version=774, etag=b"etag_blob",) - + 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.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2174,7 +2161,7 @@ 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 = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2182,16 +2169,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + 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.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2202,22 +2188,18 @@ async def test_get_iam_policy_async( 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.Policy(version=774, etag=b"etag_blob",) + 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.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2227,17 +2209,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.GetIamPolicyRequest() + 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.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2252,17 +2234,19 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.GetIamPolicyRequest() + 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.Policy()) - + 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. @@ -2276,29 +2260,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.Policy() - + 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",) @@ -2307,31 +2289,32 @@ def test_get_iam_policy_flattened(): # 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 = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=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.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + 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.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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",) @@ -2340,27 +2323,28 @@ async def test_get_iam_policy_flattened_async(): # 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 = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_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.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2372,22 +2356,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + 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.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2399,7 +2379,7 @@ 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 = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2409,16 +2389,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + 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.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2431,20 +2411,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + 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.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2454,19 +2433,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2481,11 +2460,14 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2493,9 +2475,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2509,14 +2490,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -2527,15 +2507,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2546,20 +2525,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2567,17 +2544,19 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2589,21 +2568,21 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2613,7 +2592,7 @@ def test_create_backup( transport: str = "grpc", request_type=gsad_backup.CreateBackupRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2624,13 +2603,11 @@ def test_create_backup( with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.CreateBackupRequest() # Establish that the response is the type that we expect. @@ -2645,7 +2622,7 @@ def test_create_backup_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2653,7 +2630,6 @@ def test_create_backup_empty_call(): client.create_backup() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.CreateBackupRequest() @@ -2662,7 +2638,7 @@ async def test_create_backup_async( transport: str = "grpc_asyncio", request_type=gsad_backup.CreateBackupRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2675,13 +2651,11 @@ async def test_create_backup_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.CreateBackupRequest() # Establish that the response is the type that we expect. @@ -2694,17 +2668,17 @@ async def test_create_backup_async_from_dict(): def test_create_backup_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gsad_backup.CreateBackupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_backup), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup(request) # Establish that the underlying gRPC stub method was called. @@ -2719,11 +2693,14 @@ def test_create_backup_field_headers(): @pytest.mark.asyncio async def test_create_backup_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gsad_backup.CreateBackupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2731,7 +2708,6 @@ async def test_create_backup_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_backup(request) # Establish that the underlying gRPC stub method was called. @@ -2745,13 +2721,12 @@ async def test_create_backup_field_headers_async(): def test_create_backup_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_backup( @@ -2764,16 +2739,13 @@ def test_create_backup_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].backup == gsad_backup.Backup(database="database_value") - assert args[0].backup_id == "backup_id_value" def test_create_backup_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2788,7 +2760,9 @@ def test_create_backup_flattened_error(): @pytest.mark.asyncio async def test_create_backup_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_backup), "__call__") as call: @@ -2810,17 +2784,16 @@ async def test_create_backup_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].backup == gsad_backup.Backup(database="database_value") - assert args[0].backup_id == "backup_id_value" @pytest.mark.asyncio async def test_create_backup_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2835,7 +2808,7 @@ async def test_create_backup_flattened_error_async(): def test_get_backup(transport: str = "grpc", request_type=backup.GetBackupRequest): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2852,27 +2825,19 @@ def test_get_backup(transport: str = "grpc", request_type=backup.GetBackupReques state=backup.Backup.State.CREATING, referencing_databases=["referencing_databases_value"], ) - response = client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == backup.GetBackupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, backup.Backup) - assert response.database == "database_value" - assert response.name == "name_value" - assert response.size_bytes == 1089 - assert response.state == backup.Backup.State.CREATING - assert response.referencing_databases == ["referencing_databases_value"] @@ -2884,7 +2849,7 @@ def test_get_backup_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2892,7 +2857,6 @@ def test_get_backup_empty_call(): client.get_backup() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == backup.GetBackupRequest() @@ -2901,7 +2865,7 @@ async def test_get_backup_async( transport: str = "grpc_asyncio", request_type=backup.GetBackupRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2920,26 +2884,19 @@ async def test_get_backup_async( referencing_databases=["referencing_databases_value"], ) ) - response = await client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == backup.GetBackupRequest() # Establish that the response is the type that we expect. assert isinstance(response, backup.Backup) - assert response.database == "database_value" - assert response.name == "name_value" - assert response.size_bytes == 1089 - assert response.state == backup.Backup.State.CREATING - assert response.referencing_databases == ["referencing_databases_value"] @@ -2949,17 +2906,17 @@ async def test_get_backup_async_from_dict(): def test_get_backup_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.GetBackupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_backup), "__call__") as call: call.return_value = backup.Backup() - client.get_backup(request) # Establish that the underlying gRPC stub method was called. @@ -2974,17 +2931,19 @@ def test_get_backup_field_headers(): @pytest.mark.asyncio async def test_get_backup_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.GetBackupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backup.Backup()) - await client.get_backup(request) # Establish that the underlying gRPC stub method was called. @@ -2998,13 +2957,12 @@ async def test_get_backup_field_headers_async(): def test_get_backup_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = backup.Backup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_backup(name="name_value",) @@ -3013,12 +2971,11 @@ def test_get_backup_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_backup_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3030,7 +2987,9 @@ def test_get_backup_flattened_error(): @pytest.mark.asyncio async def test_get_backup_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_backup), "__call__") as call: @@ -3046,13 +3005,14 @@ async def test_get_backup_flattened_async(): # 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_backup_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3066,7 +3026,7 @@ def test_update_backup( transport: str = "grpc", request_type=gsad_backup.UpdateBackupRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3083,27 +3043,19 @@ def test_update_backup( state=gsad_backup.Backup.State.CREATING, referencing_databases=["referencing_databases_value"], ) - response = client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.UpdateBackupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gsad_backup.Backup) - assert response.database == "database_value" - assert response.name == "name_value" - assert response.size_bytes == 1089 - assert response.state == gsad_backup.Backup.State.CREATING - assert response.referencing_databases == ["referencing_databases_value"] @@ -3115,7 +3067,7 @@ def test_update_backup_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3123,7 +3075,6 @@ def test_update_backup_empty_call(): client.update_backup() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.UpdateBackupRequest() @@ -3132,7 +3083,7 @@ async def test_update_backup_async( transport: str = "grpc_asyncio", request_type=gsad_backup.UpdateBackupRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3151,26 +3102,19 @@ async def test_update_backup_async( referencing_databases=["referencing_databases_value"], ) ) - response = await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gsad_backup.UpdateBackupRequest() # Establish that the response is the type that we expect. assert isinstance(response, gsad_backup.Backup) - assert response.database == "database_value" - assert response.name == "name_value" - assert response.size_bytes == 1089 - assert response.state == gsad_backup.Backup.State.CREATING - assert response.referencing_databases == ["referencing_databases_value"] @@ -3180,17 +3124,17 @@ async def test_update_backup_async_from_dict(): def test_update_backup_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gsad_backup.UpdateBackupRequest() + request.backup.name = "backup.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = gsad_backup.Backup() - client.update_backup(request) # Establish that the underlying gRPC stub method was called. @@ -3205,17 +3149,19 @@ def test_update_backup_field_headers(): @pytest.mark.asyncio async def test_update_backup_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gsad_backup.UpdateBackupRequest() + request.backup.name = "backup.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsad_backup.Backup()) - await client.update_backup(request) # Establish that the underlying gRPC stub method was called. @@ -3229,32 +3175,29 @@ async def test_update_backup_field_headers_async(): def test_update_backup_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsad_backup.Backup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_backup( backup=gsad_backup.Backup(database="database_value"), - update_mask=field_mask.FieldMask(paths=["paths_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].backup == gsad_backup.Backup(database="database_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_backup_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3262,13 +3205,15 @@ def test_update_backup_flattened_error(): client.update_backup( gsad_backup.UpdateBackupRequest(), backup=gsad_backup.Backup(database="database_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_backup_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_backup), "__call__") as call: @@ -3280,22 +3225,22 @@ async def test_update_backup_flattened_async(): # using the keyword arguments to the method. response = await client.update_backup( backup=gsad_backup.Backup(database="database_value"), - update_mask=field_mask.FieldMask(paths=["paths_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].backup == gsad_backup.Backup(database="database_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_backup_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3303,7 +3248,7 @@ async def test_update_backup_flattened_error_async(): await client.update_backup( gsad_backup.UpdateBackupRequest(), backup=gsad_backup.Backup(database="database_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3311,7 +3256,7 @@ def test_delete_backup( transport: str = "grpc", request_type=backup.DeleteBackupRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3322,13 +3267,11 @@ def test_delete_backup( with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == backup.DeleteBackupRequest() # Establish that the response is the type that we expect. @@ -3343,7 +3286,7 @@ def test_delete_backup_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3351,7 +3294,6 @@ def test_delete_backup_empty_call(): client.delete_backup() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == backup.DeleteBackupRequest() @@ -3360,7 +3302,7 @@ async def test_delete_backup_async( transport: str = "grpc_asyncio", request_type=backup.DeleteBackupRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3371,13 +3313,11 @@ async def test_delete_backup_async( with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == backup.DeleteBackupRequest() # Establish that the response is the type that we expect. @@ -3390,17 +3330,17 @@ async def test_delete_backup_async_from_dict(): def test_delete_backup_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.DeleteBackupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = None - client.delete_backup(request) # Establish that the underlying gRPC stub method was called. @@ -3415,17 +3355,19 @@ def test_delete_backup_field_headers(): @pytest.mark.asyncio async def test_delete_backup_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.DeleteBackupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. @@ -3439,13 +3381,12 @@ async def test_delete_backup_field_headers_async(): def test_delete_backup_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_backup(name="name_value",) @@ -3454,12 +3395,11 @@ def test_delete_backup_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_backup_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3471,7 +3411,9 @@ def test_delete_backup_flattened_error(): @pytest.mark.asyncio async def test_delete_backup_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: @@ -3487,13 +3429,14 @@ async def test_delete_backup_flattened_async(): # 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_backup_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3505,7 +3448,7 @@ async def test_delete_backup_flattened_error_async(): def test_list_backups(transport: str = "grpc", request_type=backup.ListBackupsRequest): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3518,19 +3461,15 @@ def test_list_backups(transport: str = "grpc", request_type=backup.ListBackupsRe call.return_value = backup.ListBackupsResponse( next_page_token="next_page_token_value", ) - response = client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsPager) - assert response.next_page_token == "next_page_token_value" @@ -3542,7 +3481,7 @@ def test_list_backups_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3550,7 +3489,6 @@ def test_list_backups_empty_call(): client.list_backups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupsRequest() @@ -3559,7 +3497,7 @@ async def test_list_backups_async( transport: str = "grpc_asyncio", request_type=backup.ListBackupsRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3572,18 +3510,15 @@ async def test_list_backups_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( backup.ListBackupsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListBackupsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -3593,17 +3528,17 @@ async def test_list_backups_async_from_dict(): def test_list_backups_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.ListBackupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_backups), "__call__") as call: call.return_value = backup.ListBackupsResponse() - client.list_backups(request) # Establish that the underlying gRPC stub method was called. @@ -3618,11 +3553,14 @@ def test_list_backups_field_headers(): @pytest.mark.asyncio async def test_list_backups_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.ListBackupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3630,7 +3568,6 @@ async def test_list_backups_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( backup.ListBackupsResponse() ) - await client.list_backups(request) # Establish that the underlying gRPC stub method was called. @@ -3644,13 +3581,12 @@ async def test_list_backups_field_headers_async(): def test_list_backups_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = backup.ListBackupsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_backups(parent="parent_value",) @@ -3659,12 +3595,11 @@ def test_list_backups_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_backups_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3676,7 +3611,9 @@ def test_list_backups_flattened_error(): @pytest.mark.asyncio async def test_list_backups_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_backups), "__call__") as call: @@ -3694,13 +3631,14 @@ async def test_list_backups_flattened_async(): # 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_backups_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3711,7 +3649,7 @@ async def test_list_backups_flattened_error_async(): def test_list_backups_pager(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_backups), "__call__") as call: @@ -3743,7 +3681,7 @@ def test_list_backups_pager(): def test_list_backups_pages(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_backups), "__call__") as call: @@ -3767,7 +3705,7 @@ def test_list_backups_pages(): @pytest.mark.asyncio async def test_list_backups_async_pager(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3798,7 +3736,7 @@ async def test_list_backups_async_pager(): @pytest.mark.asyncio async def test_list_backups_async_pages(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3828,7 +3766,7 @@ def test_restore_database( transport: str = "grpc", request_type=spanner_database_admin.RestoreDatabaseRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3839,13 +3777,11 @@ def test_restore_database( with mock.patch.object(type(client.transport.restore_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.RestoreDatabaseRequest() # Establish that the response is the type that we expect. @@ -3860,7 +3796,7 @@ def test_restore_database_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3868,7 +3804,6 @@ def test_restore_database_empty_call(): client.restore_database() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.RestoreDatabaseRequest() @@ -3878,7 +3813,7 @@ async def test_restore_database_async( request_type=spanner_database_admin.RestoreDatabaseRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3891,13 +3826,11 @@ async def test_restore_database_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_database(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.RestoreDatabaseRequest() # Establish that the response is the type that we expect. @@ -3910,17 +3843,17 @@ async def test_restore_database_async_from_dict(): def test_restore_database_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.RestoreDatabaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_database), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_database(request) # Establish that the underlying gRPC stub method was called. @@ -3935,11 +3868,14 @@ def test_restore_database_field_headers(): @pytest.mark.asyncio async def test_restore_database_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.RestoreDatabaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3947,7 +3883,6 @@ async def test_restore_database_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_database(request) # Establish that the underlying gRPC stub method was called. @@ -3961,13 +3896,12 @@ async def test_restore_database_field_headers_async(): def test_restore_database_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_database), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.restore_database( @@ -3980,16 +3914,13 @@ def test_restore_database_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].database_id == "database_id_value" - assert args[0].backup == "backup_value" def test_restore_database_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4004,7 +3935,9 @@ def test_restore_database_flattened_error(): @pytest.mark.asyncio async def test_restore_database_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_database), "__call__") as call: @@ -4026,17 +3959,16 @@ async def test_restore_database_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].database_id == "database_id_value" - assert args[0].backup == "backup_value" @pytest.mark.asyncio async def test_restore_database_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4054,7 +3986,7 @@ def test_list_database_operations( request_type=spanner_database_admin.ListDatabaseOperationsRequest, ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4069,19 +4001,15 @@ def test_list_database_operations( call.return_value = spanner_database_admin.ListDatabaseOperationsResponse( next_page_token="next_page_token_value", ) - response = client.list_database_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabaseOperationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDatabaseOperationsPager) - assert response.next_page_token == "next_page_token_value" @@ -4093,7 +4021,7 @@ def test_list_database_operations_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4103,7 +4031,6 @@ def test_list_database_operations_empty_call(): client.list_database_operations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabaseOperationsRequest() @@ -4113,7 +4040,7 @@ async def test_list_database_operations_async( request_type=spanner_database_admin.ListDatabaseOperationsRequest, ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4130,18 +4057,15 @@ async def test_list_database_operations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_database_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_database_admin.ListDatabaseOperationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDatabaseOperationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4151,11 +4075,12 @@ async def test_list_database_operations_async_from_dict(): def test_list_database_operations_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.ListDatabaseOperationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4163,7 +4088,6 @@ def test_list_database_operations_field_headers(): type(client.transport.list_database_operations), "__call__" ) as call: call.return_value = spanner_database_admin.ListDatabaseOperationsResponse() - client.list_database_operations(request) # Establish that the underlying gRPC stub method was called. @@ -4178,11 +4102,14 @@ def test_list_database_operations_field_headers(): @pytest.mark.asyncio async def test_list_database_operations_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_database_admin.ListDatabaseOperationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4192,7 +4119,6 @@ async def test_list_database_operations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_database_admin.ListDatabaseOperationsResponse() ) - await client.list_database_operations(request) # Establish that the underlying gRPC stub method was called. @@ -4206,7 +4132,7 @@ async def test_list_database_operations_field_headers_async(): def test_list_database_operations_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4214,7 +4140,6 @@ def test_list_database_operations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = spanner_database_admin.ListDatabaseOperationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_database_operations(parent="parent_value",) @@ -4223,12 +4148,11 @@ def test_list_database_operations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_database_operations_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4241,7 +4165,9 @@ def test_list_database_operations_flattened_error(): @pytest.mark.asyncio async def test_list_database_operations_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4261,13 +4187,14 @@ async def test_list_database_operations_flattened_async(): # 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_database_operations_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4279,7 +4206,7 @@ async def test_list_database_operations_flattened_error_async(): def test_list_database_operations_pager(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4289,9 +4216,9 @@ def test_list_database_operations_pager(): call.side_effect = ( spanner_database_admin.ListDatabaseOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), @@ -4299,10 +4226,10 @@ def test_list_database_operations_pager(): operations=[], next_page_token="def", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4317,11 +4244,11 @@ def test_list_database_operations_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, operations.Operation) for i in results) + assert all(isinstance(i, operations_pb2.Operation) for i in results) def test_list_database_operations_pages(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4331,9 +4258,9 @@ def test_list_database_operations_pages(): call.side_effect = ( spanner_database_admin.ListDatabaseOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), @@ -4341,10 +4268,10 @@ def test_list_database_operations_pages(): operations=[], next_page_token="def", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4355,7 +4282,7 @@ def test_list_database_operations_pages(): @pytest.mark.asyncio async def test_list_database_operations_async_pager(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4367,9 +4294,9 @@ async def test_list_database_operations_async_pager(): call.side_effect = ( spanner_database_admin.ListDatabaseOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), @@ -4377,10 +4304,10 @@ async def test_list_database_operations_async_pager(): operations=[], next_page_token="def", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4391,12 +4318,12 @@ async def test_list_database_operations_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, operations.Operation) for i in responses) + assert all(isinstance(i, operations_pb2.Operation) for i in responses) @pytest.mark.asyncio async def test_list_database_operations_async_pages(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4408,9 +4335,9 @@ async def test_list_database_operations_async_pages(): call.side_effect = ( spanner_database_admin.ListDatabaseOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), @@ -4418,10 +4345,10 @@ async def test_list_database_operations_async_pages(): operations=[], next_page_token="def", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), spanner_database_admin.ListDatabaseOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4436,7 +4363,7 @@ def test_list_backup_operations( transport: str = "grpc", request_type=backup.ListBackupOperationsRequest ): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4451,19 +4378,15 @@ def test_list_backup_operations( call.return_value = backup.ListBackupOperationsResponse( next_page_token="next_page_token_value", ) - response = client.list_backup_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupOperationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupOperationsPager) - assert response.next_page_token == "next_page_token_value" @@ -4475,7 +4398,7 @@ def test_list_backup_operations_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4485,7 +4408,6 @@ def test_list_backup_operations_empty_call(): client.list_backup_operations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupOperationsRequest() @@ -4494,7 +4416,7 @@ async def test_list_backup_operations_async( transport: str = "grpc_asyncio", request_type=backup.ListBackupOperationsRequest ): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4511,18 +4433,15 @@ async def test_list_backup_operations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_backup_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == backup.ListBackupOperationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListBackupOperationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4532,11 +4451,12 @@ async def test_list_backup_operations_async_from_dict(): def test_list_backup_operations_field_headers(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.ListBackupOperationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4544,7 +4464,6 @@ def test_list_backup_operations_field_headers(): type(client.transport.list_backup_operations), "__call__" ) as call: call.return_value = backup.ListBackupOperationsResponse() - client.list_backup_operations(request) # Establish that the underlying gRPC stub method was called. @@ -4559,11 +4478,14 @@ def test_list_backup_operations_field_headers(): @pytest.mark.asyncio async def test_list_backup_operations_field_headers_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = backup.ListBackupOperationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4573,7 +4495,6 @@ async def test_list_backup_operations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( backup.ListBackupOperationsResponse() ) - await client.list_backup_operations(request) # Establish that the underlying gRPC stub method was called. @@ -4587,7 +4508,7 @@ async def test_list_backup_operations_field_headers_async(): def test_list_backup_operations_flattened(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4595,7 +4516,6 @@ def test_list_backup_operations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = backup.ListBackupOperationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_backup_operations(parent="parent_value",) @@ -4604,12 +4524,11 @@ def test_list_backup_operations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_backup_operations_flattened_error(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4621,7 +4540,9 @@ def test_list_backup_operations_flattened_error(): @pytest.mark.asyncio async def test_list_backup_operations_flattened_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4641,13 +4562,14 @@ async def test_list_backup_operations_flattened_async(): # 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_backup_operations_flattened_error_async(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4658,7 +4580,7 @@ async def test_list_backup_operations_flattened_error_async(): def test_list_backup_operations_pager(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4668,18 +4590,18 @@ def test_list_backup_operations_pager(): call.side_effect = ( backup.ListBackupOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), backup.ListBackupOperationsResponse(operations=[], next_page_token="def",), backup.ListBackupOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), backup.ListBackupOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4694,11 +4616,11 @@ def test_list_backup_operations_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, operations.Operation) for i in results) + assert all(isinstance(i, operations_pb2.Operation) for i in results) def test_list_backup_operations_pages(): - client = DatabaseAdminClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4708,18 +4630,18 @@ def test_list_backup_operations_pages(): call.side_effect = ( backup.ListBackupOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), backup.ListBackupOperationsResponse(operations=[], next_page_token="def",), backup.ListBackupOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), backup.ListBackupOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4730,7 +4652,7 @@ def test_list_backup_operations_pages(): @pytest.mark.asyncio async def test_list_backup_operations_async_pager(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4742,18 +4664,18 @@ async def test_list_backup_operations_async_pager(): call.side_effect = ( backup.ListBackupOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), backup.ListBackupOperationsResponse(operations=[], next_page_token="def",), backup.ListBackupOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), backup.ListBackupOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4764,12 +4686,12 @@ async def test_list_backup_operations_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, operations.Operation) for i in responses) + assert all(isinstance(i, operations_pb2.Operation) for i in responses) @pytest.mark.asyncio async def test_list_backup_operations_async_pages(): - client = DatabaseAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DatabaseAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4781,18 +4703,18 @@ async def test_list_backup_operations_async_pages(): call.side_effect = ( backup.ListBackupOperationsResponse( operations=[ - operations.Operation(), - operations.Operation(), - operations.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), + operations_pb2.Operation(), ], next_page_token="abc", ), backup.ListBackupOperationsResponse(operations=[], next_page_token="def",), backup.ListBackupOperationsResponse( - operations=[operations.Operation(),], next_page_token="ghi", + operations=[operations_pb2.Operation(),], next_page_token="ghi", ), backup.ListBackupOperationsResponse( - operations=[operations.Operation(), operations.Operation(),], + operations=[operations_pb2.Operation(), operations_pb2.Operation(),], ), RuntimeError, ) @@ -4806,16 +4728,16 @@ async def test_list_backup_operations_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DatabaseAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DatabaseAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DatabaseAdminClient( @@ -4825,7 +4747,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DatabaseAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DatabaseAdminClient( @@ -4836,7 +4758,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DatabaseAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DatabaseAdminClient(transport=transport) assert client.transport is transport @@ -4845,13 +4767,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DatabaseAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DatabaseAdminGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -4866,23 +4788,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = DatabaseAdminClient(credentials=credentials.AnonymousCredentials(),) + client = DatabaseAdminClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DatabaseAdminGrpcTransport,) def test_database_admin_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DatabaseAdminTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -4894,7 +4816,7 @@ def test_database_admin_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DatabaseAdminTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -4928,15 +4850,40 @@ def test_database_admin_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_database_admin_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.spanner_admin_database_v1.services.database_admin.transports.DatabaseAdminTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DatabaseAdminTransport( + 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", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_database_admin_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.spanner_admin_database_v1.services.database_admin.transports.DatabaseAdminTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DatabaseAdminTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -4952,19 +4899,36 @@ def test_database_admin_base_transport_with_credentials_file(): def test_database_admin_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.spanner_admin_database_v1.services.database_admin.transports.DatabaseAdminTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DatabaseAdminTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_database_admin_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DatabaseAdminClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_database_admin_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) DatabaseAdminClient() adc.assert_called_once_with( scopes=( @@ -4975,14 +4939,44 @@ def test_database_admin_auth_adc(): ) -def test_database_admin_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.DatabaseAdminGrpcTransport, + transports.DatabaseAdminGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_database_admin_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.DatabaseAdminGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DatabaseAdminGrpcTransport, + transports.DatabaseAdminGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_database_admin_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -4992,6 +4986,121 @@ def test_database_admin_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DatabaseAdminGrpcTransport, grpc_helpers), + (transports.DatabaseAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_database_admin_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + scopes=["1", "2"], + default_host="spanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DatabaseAdminGrpcTransport, grpc_helpers), + (transports.DatabaseAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_database_admin_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DatabaseAdminGrpcTransport, grpc_helpers), + (transports.DatabaseAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_database_admin_transport_create_channel_user_scopes( + 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( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -5000,7 +5109,7 @@ def test_database_admin_transport_auth_adc(): ], ) def test_database_admin_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -5042,7 +5151,7 @@ def test_database_admin_grpc_transport_client_cert_source_for_mtls(transport_cla def test_database_admin_host_no_port(): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com" ), @@ -5052,7 +5161,7 @@ def test_database_admin_host_no_port(): def test_database_admin_host_with_port(): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com:8000" ), @@ -5106,9 +5215,9 @@ def test_database_admin_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -5190,7 +5299,7 @@ def test_database_admin_transport_channel_mtls_with_adc(transport_class): def test_database_admin_grpc_lro_client(): client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -5203,7 +5312,7 @@ def test_database_admin_grpc_lro_client(): def test_database_admin_grpc_lro_async_client(): client = DatabaseAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -5218,7 +5327,6 @@ def test_backup_path(): project = "squid" instance = "clam" backup = "whelk" - expected = "projects/{project}/instances/{instance}/backups/{backup}".format( project=project, instance=instance, backup=backup, ) @@ -5244,7 +5352,6 @@ def test_crypto_key_path(): location = "mussel" key_ring = "winkle" crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) @@ -5274,7 +5381,6 @@ def test_crypto_key_version_path(): key_ring = "oyster" crypto_key = "nudibranch" crypto_key_version = "cuttlefish" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, location=location, @@ -5307,7 +5413,6 @@ def test_database_path(): project = "squid" instance = "clam" database = "whelk" - expected = "projects/{project}/instances/{instance}/databases/{database}".format( project=project, instance=instance, database=database, ) @@ -5331,7 +5436,6 @@ def test_parse_database_path(): def test_instance_path(): project = "cuttlefish" instance = "mussel" - expected = "projects/{project}/instances/{instance}".format( project=project, instance=instance, ) @@ -5353,7 +5457,6 @@ def test_parse_instance_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5374,7 +5477,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = DatabaseAdminClient.common_folder_path(folder) assert expected == actual @@ -5393,7 +5495,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = DatabaseAdminClient.common_organization_path(organization) assert expected == actual @@ -5412,7 +5513,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = DatabaseAdminClient.common_project_path(project) assert expected == actual @@ -5432,7 +5532,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -5459,7 +5558,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DatabaseAdminTransport, "_prep_wrapped_messages" ) as prep: client = DatabaseAdminClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -5468,6 +5567,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DatabaseAdminClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/spanner_admin_instance_v1/__init__.py b/tests/unit/gapic/spanner_admin_instance_v1/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/tests/unit/gapic/spanner_admin_instance_v1/__init__.py +++ b/tests/unit/gapic/spanner_admin_instance_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/spanner_admin_instance_v1/test_instance_admin.py b/tests/unit/gapic/spanner_admin_instance_v1/test_instance_admin.py index b64c5eca33..b36c820cf5 100644 --- a/tests/unit/gapic/spanner_admin_instance_v1/test_instance_admin.py +++ b/tests/unit/gapic/spanner_admin_instance_v1/test_instance_admin.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.spanner_admin_instance_v1.services.instance_admin import ( InstanceAdminAsyncClient, @@ -43,15 +42,44 @@ ) from google.cloud.spanner_admin_instance_v1.services.instance_admin import pagers from google.cloud.spanner_admin_instance_v1.services.instance_admin import transports +from google.cloud.spanner_admin_instance_v1.services.instance_admin.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.spanner_admin_instance_v1.services.instance_admin.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -102,7 +130,7 @@ def test__get_default_mtls_endpoint(): "client_class", [InstanceAdminClient, InstanceAdminAsyncClient,] ) def test_instance_admin_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -119,7 +147,7 @@ def test_instance_admin_client_from_service_account_info(client_class): "client_class", [InstanceAdminClient, InstanceAdminAsyncClient,] ) def test_instance_admin_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -172,7 +200,7 @@ def test_instance_admin_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InstanceAdminClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -461,7 +489,7 @@ def test_list_instance_configs( request_type=spanner_instance_admin.ListInstanceConfigsRequest, ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -476,19 +504,15 @@ def test_list_instance_configs( call.return_value = spanner_instance_admin.ListInstanceConfigsResponse( next_page_token="next_page_token_value", ) - response = client.list_instance_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstanceConfigsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstanceConfigsPager) - assert response.next_page_token == "next_page_token_value" @@ -500,7 +524,7 @@ def test_list_instance_configs_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -510,7 +534,6 @@ def test_list_instance_configs_empty_call(): client.list_instance_configs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstanceConfigsRequest() @@ -520,7 +543,7 @@ async def test_list_instance_configs_async( request_type=spanner_instance_admin.ListInstanceConfigsRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -537,18 +560,15 @@ async def test_list_instance_configs_async( next_page_token="next_page_token_value", ) ) - response = await client.list_instance_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstanceConfigsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListInstanceConfigsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -558,11 +578,12 @@ async def test_list_instance_configs_async_from_dict(): def test_list_instance_configs_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.ListInstanceConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -570,7 +591,6 @@ def test_list_instance_configs_field_headers(): type(client.transport.list_instance_configs), "__call__" ) as call: call.return_value = spanner_instance_admin.ListInstanceConfigsResponse() - client.list_instance_configs(request) # Establish that the underlying gRPC stub method was called. @@ -585,11 +605,14 @@ def test_list_instance_configs_field_headers(): @pytest.mark.asyncio async def test_list_instance_configs_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.ListInstanceConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -599,7 +622,6 @@ async def test_list_instance_configs_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_instance_admin.ListInstanceConfigsResponse() ) - await client.list_instance_configs(request) # Establish that the underlying gRPC stub method was called. @@ -613,7 +635,7 @@ async def test_list_instance_configs_field_headers_async(): def test_list_instance_configs_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -621,7 +643,6 @@ def test_list_instance_configs_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = spanner_instance_admin.ListInstanceConfigsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_instance_configs(parent="parent_value",) @@ -630,12 +651,11 @@ def test_list_instance_configs_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_instance_configs_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -647,7 +667,9 @@ def test_list_instance_configs_flattened_error(): @pytest.mark.asyncio async def test_list_instance_configs_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -667,13 +689,14 @@ async def test_list_instance_configs_flattened_async(): # 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_instance_configs_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -684,7 +707,7 @@ async def test_list_instance_configs_flattened_error_async(): def test_list_instance_configs_pager(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -732,7 +755,7 @@ def test_list_instance_configs_pager(): def test_list_instance_configs_pages(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -770,7 +793,7 @@ def test_list_instance_configs_pages(): @pytest.mark.asyncio async def test_list_instance_configs_async_pager(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -817,7 +840,7 @@ async def test_list_instance_configs_async_pager(): @pytest.mark.asyncio async def test_list_instance_configs_async_pages(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -862,7 +885,7 @@ def test_get_instance_config( request_type=spanner_instance_admin.GetInstanceConfigRequest, ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -877,21 +900,16 @@ def test_get_instance_config( call.return_value = spanner_instance_admin.InstanceConfig( name="name_value", display_name="display_name_value", ) - response = client.get_instance_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner_instance_admin.InstanceConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -903,7 +921,7 @@ def test_get_instance_config_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -913,7 +931,6 @@ def test_get_instance_config_empty_call(): client.get_instance_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceConfigRequest() @@ -923,7 +940,7 @@ async def test_get_instance_config_async( request_type=spanner_instance_admin.GetInstanceConfigRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -940,20 +957,16 @@ async def test_get_instance_config_async( name="name_value", display_name="display_name_value", ) ) - response = await client.get_instance_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner_instance_admin.InstanceConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -963,11 +976,12 @@ async def test_get_instance_config_async_from_dict(): def test_get_instance_config_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.GetInstanceConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -975,7 +989,6 @@ def test_get_instance_config_field_headers(): type(client.transport.get_instance_config), "__call__" ) as call: call.return_value = spanner_instance_admin.InstanceConfig() - client.get_instance_config(request) # Establish that the underlying gRPC stub method was called. @@ -990,11 +1003,14 @@ def test_get_instance_config_field_headers(): @pytest.mark.asyncio async def test_get_instance_config_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.GetInstanceConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1004,7 +1020,6 @@ async def test_get_instance_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_instance_admin.InstanceConfig() ) - await client.get_instance_config(request) # Establish that the underlying gRPC stub method was called. @@ -1018,7 +1033,7 @@ async def test_get_instance_config_field_headers_async(): def test_get_instance_config_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1026,7 +1041,6 @@ def test_get_instance_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = spanner_instance_admin.InstanceConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_instance_config(name="name_value",) @@ -1035,12 +1049,11 @@ def test_get_instance_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_instance_config_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1052,7 +1065,9 @@ def test_get_instance_config_flattened_error(): @pytest.mark.asyncio async def test_get_instance_config_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1072,13 +1087,14 @@ async def test_get_instance_config_flattened_async(): # 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_instance_config_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1092,7 +1108,7 @@ def test_list_instances( transport: str = "grpc", request_type=spanner_instance_admin.ListInstancesRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1105,19 +1121,15 @@ def test_list_instances( call.return_value = spanner_instance_admin.ListInstancesResponse( next_page_token="next_page_token_value", ) - response = client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstancesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" @@ -1129,7 +1141,7 @@ def test_list_instances_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1137,7 +1149,6 @@ def test_list_instances_empty_call(): client.list_instances() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstancesRequest() @@ -1147,7 +1158,7 @@ async def test_list_instances_async( request_type=spanner_instance_admin.ListInstancesRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1162,18 +1173,15 @@ async def test_list_instances_async( next_page_token="next_page_token_value", ) ) - response = await client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.ListInstancesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListInstancesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1183,17 +1191,17 @@ async def test_list_instances_async_from_dict(): def test_list_instances_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.ListInstancesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: call.return_value = spanner_instance_admin.ListInstancesResponse() - client.list_instances(request) # Establish that the underlying gRPC stub method was called. @@ -1208,11 +1216,14 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.ListInstancesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1231,6 @@ async def test_list_instances_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_instance_admin.ListInstancesResponse() ) - await client.list_instances(request) # Establish that the underlying gRPC stub method was called. @@ -1234,13 +1244,12 @@ async def test_list_instances_field_headers_async(): def test_list_instances_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner_instance_admin.ListInstancesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_instances(parent="parent_value",) @@ -1249,12 +1258,11 @@ def test_list_instances_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_instances_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1266,7 +1274,9 @@ def test_list_instances_flattened_error(): @pytest.mark.asyncio async def test_list_instances_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: @@ -1284,13 +1294,14 @@ async def test_list_instances_flattened_async(): # 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_instances_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1301,7 +1312,7 @@ async def test_list_instances_flattened_error_async(): def test_list_instances_pager(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: @@ -1344,7 +1355,7 @@ def test_list_instances_pager(): def test_list_instances_pages(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: @@ -1379,7 +1390,7 @@ def test_list_instances_pages(): @pytest.mark.asyncio async def test_list_instances_async_pager(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1421,7 +1432,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstanceAdminAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1462,7 +1473,7 @@ def test_get_instance( transport: str = "grpc", request_type=spanner_instance_admin.GetInstanceRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1480,29 +1491,20 @@ def test_get_instance( state=spanner_instance_admin.Instance.State.CREATING, endpoint_uris=["endpoint_uris_value"], ) - response = client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner_instance_admin.Instance) - assert response.name == "name_value" - assert response.config == "config_value" - assert response.display_name == "display_name_value" - assert response.node_count == 1070 - assert response.state == spanner_instance_admin.Instance.State.CREATING - assert response.endpoint_uris == ["endpoint_uris_value"] @@ -1514,7 +1516,7 @@ def test_get_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1522,7 +1524,6 @@ def test_get_instance_empty_call(): client.get_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceRequest() @@ -1532,7 +1533,7 @@ async def test_get_instance_async( request_type=spanner_instance_admin.GetInstanceRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1552,28 +1553,20 @@ async def test_get_instance_async( endpoint_uris=["endpoint_uris_value"], ) ) - response = await client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.GetInstanceRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner_instance_admin.Instance) - assert response.name == "name_value" - assert response.config == "config_value" - assert response.display_name == "display_name_value" - assert response.node_count == 1070 - assert response.state == spanner_instance_admin.Instance.State.CREATING - assert response.endpoint_uris == ["endpoint_uris_value"] @@ -1583,17 +1576,17 @@ async def test_get_instance_async_from_dict(): def test_get_instance_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.GetInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_instance), "__call__") as call: call.return_value = spanner_instance_admin.Instance() - client.get_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1608,11 +1601,14 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.GetInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1620,7 +1616,6 @@ async def test_get_instance_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner_instance_admin.Instance() ) - await client.get_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1634,13 +1629,12 @@ async def test_get_instance_field_headers_async(): def test_get_instance_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner_instance_admin.Instance() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_instance(name="name_value",) @@ -1649,12 +1643,11 @@ def test_get_instance_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_instance_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1666,7 +1659,9 @@ def test_get_instance_flattened_error(): @pytest.mark.asyncio async def test_get_instance_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_instance), "__call__") as call: @@ -1684,13 +1679,14 @@ async def test_get_instance_flattened_async(): # 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_instance_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1704,7 +1700,7 @@ def test_create_instance( transport: str = "grpc", request_type=spanner_instance_admin.CreateInstanceRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1715,13 +1711,11 @@ def test_create_instance( with mock.patch.object(type(client.transport.create_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.CreateInstanceRequest() # Establish that the response is the type that we expect. @@ -1736,7 +1730,7 @@ def test_create_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1744,7 +1738,6 @@ def test_create_instance_empty_call(): client.create_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.CreateInstanceRequest() @@ -1754,7 +1747,7 @@ async def test_create_instance_async( request_type=spanner_instance_admin.CreateInstanceRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1767,13 +1760,11 @@ async def test_create_instance_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.CreateInstanceRequest() # Establish that the response is the type that we expect. @@ -1786,17 +1777,17 @@ async def test_create_instance_async_from_dict(): def test_create_instance_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.CreateInstanceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1811,11 +1802,14 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio async def test_create_instance_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.CreateInstanceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1823,7 +1817,6 @@ async def test_create_instance_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1837,13 +1830,12 @@ async def test_create_instance_field_headers_async(): def test_create_instance_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_instance( @@ -1856,16 +1848,13 @@ def test_create_instance_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].instance_id == "instance_id_value" - assert args[0].instance == spanner_instance_admin.Instance(name="name_value") def test_create_instance_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1880,7 +1869,9 @@ def test_create_instance_flattened_error(): @pytest.mark.asyncio async def test_create_instance_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_instance), "__call__") as call: @@ -1902,17 +1893,16 @@ async def test_create_instance_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].instance_id == "instance_id_value" - assert args[0].instance == spanner_instance_admin.Instance(name="name_value") @pytest.mark.asyncio async def test_create_instance_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1929,7 +1919,7 @@ def test_update_instance( transport: str = "grpc", request_type=spanner_instance_admin.UpdateInstanceRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1940,13 +1930,11 @@ def test_update_instance( with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.UpdateInstanceRequest() # Establish that the response is the type that we expect. @@ -1961,7 +1949,7 @@ def test_update_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1969,7 +1957,6 @@ def test_update_instance_empty_call(): client.update_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.UpdateInstanceRequest() @@ -1979,7 +1966,7 @@ async def test_update_instance_async( request_type=spanner_instance_admin.UpdateInstanceRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1992,13 +1979,11 @@ async def test_update_instance_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.UpdateInstanceRequest() # Establish that the response is the type that we expect. @@ -2011,17 +1996,17 @@ async def test_update_instance_async_from_dict(): def test_update_instance_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.UpdateInstanceRequest() + request.instance.name = "instance.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_instance(request) # Establish that the underlying gRPC stub method was called. @@ -2038,11 +2023,14 @@ def test_update_instance_field_headers(): @pytest.mark.asyncio async def test_update_instance_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.UpdateInstanceRequest() + request.instance.name = "instance.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2050,7 +2038,6 @@ async def test_update_instance_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_instance(request) # Establish that the underlying gRPC stub method was called. @@ -2066,32 +2053,29 @@ async def test_update_instance_field_headers_async(): def test_update_instance_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_instance( instance=spanner_instance_admin.Instance(name="name_value"), - field_mask=gp_field_mask.FieldMask(paths=["paths_value"]), + field_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].instance == spanner_instance_admin.Instance(name="name_value") - - assert args[0].field_mask == gp_field_mask.FieldMask(paths=["paths_value"]) + assert args[0].field_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_instance_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2099,13 +2083,15 @@ def test_update_instance_flattened_error(): client.update_instance( spanner_instance_admin.UpdateInstanceRequest(), instance=spanner_instance_admin.Instance(name="name_value"), - field_mask=gp_field_mask.FieldMask(paths=["paths_value"]), + field_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_instance_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_instance), "__call__") as call: @@ -2119,22 +2105,22 @@ async def test_update_instance_flattened_async(): # using the keyword arguments to the method. response = await client.update_instance( instance=spanner_instance_admin.Instance(name="name_value"), - field_mask=gp_field_mask.FieldMask(paths=["paths_value"]), + field_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].instance == spanner_instance_admin.Instance(name="name_value") - - assert args[0].field_mask == gp_field_mask.FieldMask(paths=["paths_value"]) + assert args[0].field_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_instance_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2142,7 +2128,7 @@ async def test_update_instance_flattened_error_async(): await client.update_instance( spanner_instance_admin.UpdateInstanceRequest(), instance=spanner_instance_admin.Instance(name="name_value"), - field_mask=gp_field_mask.FieldMask(paths=["paths_value"]), + field_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2150,7 +2136,7 @@ def test_delete_instance( transport: str = "grpc", request_type=spanner_instance_admin.DeleteInstanceRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2161,13 +2147,11 @@ def test_delete_instance( with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.DeleteInstanceRequest() # Establish that the response is the type that we expect. @@ -2182,7 +2166,7 @@ def test_delete_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2190,7 +2174,6 @@ def test_delete_instance_empty_call(): client.delete_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.DeleteInstanceRequest() @@ -2200,7 +2183,7 @@ async def test_delete_instance_async( request_type=spanner_instance_admin.DeleteInstanceRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2211,13 +2194,11 @@ async def test_delete_instance_async( with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner_instance_admin.DeleteInstanceRequest() # Establish that the response is the type that we expect. @@ -2230,17 +2211,17 @@ async def test_delete_instance_async_from_dict(): def test_delete_instance_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.DeleteInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value = None - client.delete_instance(request) # Establish that the underlying gRPC stub method was called. @@ -2255,17 +2236,19 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner_instance_admin.DeleteInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. @@ -2279,13 +2262,12 @@ async def test_delete_instance_field_headers_async(): def test_delete_instance_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_instance(name="name_value",) @@ -2294,12 +2276,11 @@ def test_delete_instance_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_instance_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2311,7 +2292,9 @@ def test_delete_instance_flattened_error(): @pytest.mark.asyncio async def test_delete_instance_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: @@ -2327,13 +2310,14 @@ async def test_delete_instance_flattened_async(): # 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_instance_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2344,10 +2328,10 @@ async def test_delete_instance_flattened_error_async(): def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2357,22 +2341,17 @@ def test_set_iam_policy( # 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.Policy(version=774, etag=b"etag_blob",) - + 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.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2384,7 +2363,7 @@ 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 = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2392,16 +2371,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + 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.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2412,22 +2390,18 @@ async def test_set_iam_policy_async( 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.Policy(version=774, etag=b"etag_blob",) + 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.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2437,17 +2411,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.SetIamPolicyRequest() + 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.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2462,17 +2436,19 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.SetIamPolicyRequest() + 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.Policy()) - + 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. @@ -2486,29 +2462,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.Policy() - + 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",) @@ -2517,31 +2491,32 @@ def test_set_iam_policy_flattened(): # 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 = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=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.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + 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.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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",) @@ -2550,27 +2525,28 @@ async def test_set_iam_policy_flattened_async(): # 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 = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_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.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2580,22 +2556,17 @@ def test_get_iam_policy( # 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.Policy(version=774, etag=b"etag_blob",) - + 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.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2607,7 +2578,7 @@ 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 = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2615,16 +2586,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + 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.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2635,22 +2605,18 @@ async def test_get_iam_policy_async( 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.Policy(version=774, etag=b"etag_blob",) + 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.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2660,17 +2626,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.GetIamPolicyRequest() + 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.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2685,17 +2651,19 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.GetIamPolicyRequest() + 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.Policy()) - + 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. @@ -2709,29 +2677,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.Policy() - + 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",) @@ -2740,31 +2706,32 @@ def test_get_iam_policy_flattened(): # 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 = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=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.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + 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.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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",) @@ -2773,27 +2740,28 @@ async def test_get_iam_policy_flattened_async(): # 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 = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_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.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2805,22 +2773,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + 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.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2832,7 +2796,7 @@ 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 = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2842,16 +2806,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + 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.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2864,20 +2828,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + 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.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2887,19 +2850,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value 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.TestIamPermissionsRequest() + 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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2914,11 +2877,14 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value 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.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2926,9 +2892,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2942,14 +2907,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -2960,15 +2924,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(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.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2979,20 +2942,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -3000,17 +2961,19 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + 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.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -3022,21 +2985,21 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = InstanceAdminAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -3045,16 +3008,16 @@ async def test_test_iam_permissions_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstanceAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstanceAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceAdminClient( @@ -3064,7 +3027,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstanceAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceAdminClient( @@ -3075,7 +3038,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstanceAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstanceAdminClient(transport=transport) assert client.transport is transport @@ -3084,13 +3047,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.InstanceAdminGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.InstanceAdminGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3105,23 +3068,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = InstanceAdminClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceAdminClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.InstanceAdminGrpcTransport,) def test_instance_admin_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstanceAdminTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3133,7 +3096,7 @@ def test_instance_admin_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstanceAdminTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3160,15 +3123,40 @@ def test_instance_admin_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_instance_admin_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.spanner_admin_instance_v1.services.instance_admin.transports.InstanceAdminTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstanceAdminTransport( + 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", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_instance_admin_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.spanner_admin_instance_v1.services.instance_admin.transports.InstanceAdminTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceAdminTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3184,19 +3172,36 @@ def test_instance_admin_base_transport_with_credentials_file(): def test_instance_admin_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.spanner_admin_instance_v1.services.instance_admin.transports.InstanceAdminTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceAdminTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instance_admin_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstanceAdminClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_instance_admin_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) InstanceAdminClient() adc.assert_called_once_with( scopes=( @@ -3207,14 +3212,44 @@ def test_instance_admin_auth_adc(): ) -def test_instance_admin_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstanceAdminGrpcTransport, + transports.InstanceAdminGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_instance_admin_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.InstanceAdminGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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", + "https://www.googleapis.com/auth/spanner.admin", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstanceAdminGrpcTransport, + transports.InstanceAdminGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_instance_admin_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -3224,6 +3259,121 @@ def test_instance_admin_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstanceAdminGrpcTransport, grpc_helpers), + (transports.InstanceAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_instance_admin_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + scopes=["1", "2"], + default_host="spanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstanceAdminGrpcTransport, grpc_helpers), + (transports.InstanceAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_instance_admin_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.admin", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstanceAdminGrpcTransport, grpc_helpers), + (transports.InstanceAdminGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_instance_admin_transport_create_channel_user_scopes( + 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( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -3232,7 +3382,7 @@ def test_instance_admin_transport_auth_adc(): ], ) def test_instance_admin_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3274,7 +3424,7 @@ def test_instance_admin_grpc_transport_client_cert_source_for_mtls(transport_cla def test_instance_admin_host_no_port(): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com" ), @@ -3284,7 +3434,7 @@ def test_instance_admin_host_no_port(): def test_instance_admin_host_with_port(): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com:8000" ), @@ -3338,9 +3488,9 @@ def test_instance_admin_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3422,7 +3572,7 @@ def test_instance_admin_transport_channel_mtls_with_adc(transport_class): def test_instance_admin_grpc_lro_client(): client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3435,7 +3585,7 @@ def test_instance_admin_grpc_lro_client(): def test_instance_admin_grpc_lro_async_client(): client = InstanceAdminAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3449,7 +3599,6 @@ def test_instance_admin_grpc_lro_async_client(): def test_instance_path(): project = "squid" instance = "clam" - expected = "projects/{project}/instances/{instance}".format( project=project, instance=instance, ) @@ -3472,7 +3621,6 @@ def test_parse_instance_path(): def test_instance_config_path(): project = "oyster" instance_config = "nudibranch" - expected = "projects/{project}/instanceConfigs/{instance_config}".format( project=project, instance_config=instance_config, ) @@ -3494,7 +3642,6 @@ def test_parse_instance_config_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3515,7 +3662,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = InstanceAdminClient.common_folder_path(folder) assert expected == actual @@ -3534,7 +3680,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = InstanceAdminClient.common_organization_path(organization) assert expected == actual @@ -3553,7 +3698,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = InstanceAdminClient.common_project_path(project) assert expected == actual @@ -3573,7 +3717,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3600,7 +3743,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstanceAdminTransport, "_prep_wrapped_messages" ) as prep: client = InstanceAdminClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3609,6 +3752,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstanceAdminClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/spanner_v1/__init__.py b/tests/unit/gapic/spanner_v1/__init__.py index 42ffdf2bc4..4de65971c2 100644 --- a/tests/unit/gapic/spanner_v1/__init__.py +++ b/tests/unit/gapic/spanner_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/spanner_v1/test_spanner.py b/tests/unit/gapic/spanner_v1/test_spanner.py index 37ca9c6deb..9b57993367 100644 --- a/tests/unit/gapic/spanner_v1/test_spanner.py +++ b/tests/unit/gapic/spanner_v1/test_spanner.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,18 +23,23 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.spanner_v1.services.spanner import SpannerAsyncClient from google.cloud.spanner_v1.services.spanner import SpannerClient from google.cloud.spanner_v1.services.spanner import pagers from google.cloud.spanner_v1.services.spanner import transports +from google.cloud.spanner_v1.services.spanner.transports.base import _API_CORE_VERSION +from google.cloud.spanner_v1.services.spanner.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.spanner_v1.types import commit_response from google.cloud.spanner_v1.types import keys from google.cloud.spanner_v1.types import mutation from google.cloud.spanner_v1.types import result_set @@ -43,10 +47,34 @@ from google.cloud.spanner_v1.types import transaction from google.cloud.spanner_v1.types import type as gs_type from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -89,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SpannerClient, SpannerAsyncClient,]) def test_spanner_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -104,7 +132,7 @@ def test_spanner_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SpannerClient, SpannerAsyncClient,]) def test_spanner_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -147,7 +175,7 @@ def test_spanner_client_get_transport_class(): def test_spanner_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(SpannerClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -421,7 +449,7 @@ def test_create_session( transport: str = "grpc", request_type=spanner.CreateSessionRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -432,19 +460,15 @@ def test_create_session( with mock.patch.object(type(client.transport.create_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.Session(name="name_value",) - response = client.create_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CreateSessionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.Session) - assert response.name == "name_value" @@ -456,7 +480,7 @@ def test_create_session_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -464,7 +488,6 @@ def test_create_session_empty_call(): client.create_session() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CreateSessionRequest() @@ -473,7 +496,7 @@ async def test_create_session_async( transport: str = "grpc_asyncio", request_type=spanner.CreateSessionRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -486,18 +509,15 @@ async def test_create_session_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.Session(name="name_value",) ) - response = await client.create_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CreateSessionRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner.Session) - assert response.name == "name_value" @@ -507,17 +527,17 @@ async def test_create_session_async_from_dict(): def test_create_session_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.CreateSessionRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_session), "__call__") as call: call.return_value = spanner.Session() - client.create_session(request) # Establish that the underlying gRPC stub method was called. @@ -532,17 +552,17 @@ def test_create_session_field_headers(): @pytest.mark.asyncio async def test_create_session_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.CreateSessionRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_session), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(spanner.Session()) - await client.create_session(request) # Establish that the underlying gRPC stub method was called. @@ -556,13 +576,12 @@ async def test_create_session_field_headers_async(): def test_create_session_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.Session() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_session(database="database_value",) @@ -571,12 +590,11 @@ def test_create_session_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" def test_create_session_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -588,7 +606,7 @@ def test_create_session_flattened_error(): @pytest.mark.asyncio async def test_create_session_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_session), "__call__") as call: @@ -604,13 +622,12 @@ async def test_create_session_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" @pytest.mark.asyncio async def test_create_session_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -624,7 +641,7 @@ def test_batch_create_sessions( transport: str = "grpc", request_type=spanner.BatchCreateSessionsRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -637,17 +654,14 @@ def test_batch_create_sessions( ) as call: # Designate an appropriate return value for the call. call.return_value = spanner.BatchCreateSessionsResponse() - response = client.batch_create_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BatchCreateSessionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.BatchCreateSessionsResponse) @@ -659,7 +673,7 @@ def test_batch_create_sessions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -669,7 +683,6 @@ def test_batch_create_sessions_empty_call(): client.batch_create_sessions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BatchCreateSessionsRequest() @@ -678,7 +691,7 @@ async def test_batch_create_sessions_async( transport: str = "grpc_asyncio", request_type=spanner.BatchCreateSessionsRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -693,13 +706,11 @@ async def test_batch_create_sessions_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.BatchCreateSessionsResponse() ) - response = await client.batch_create_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BatchCreateSessionsRequest() # Establish that the response is the type that we expect. @@ -712,11 +723,12 @@ async def test_batch_create_sessions_async_from_dict(): def test_batch_create_sessions_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.BatchCreateSessionsRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -724,7 +736,6 @@ def test_batch_create_sessions_field_headers(): type(client.transport.batch_create_sessions), "__call__" ) as call: call.return_value = spanner.BatchCreateSessionsResponse() - client.batch_create_sessions(request) # Establish that the underlying gRPC stub method was called. @@ -739,11 +750,12 @@ def test_batch_create_sessions_field_headers(): @pytest.mark.asyncio async def test_batch_create_sessions_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.BatchCreateSessionsRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -753,7 +765,6 @@ async def test_batch_create_sessions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.BatchCreateSessionsResponse() ) - await client.batch_create_sessions(request) # Establish that the underlying gRPC stub method was called. @@ -767,7 +778,7 @@ async def test_batch_create_sessions_field_headers_async(): def test_batch_create_sessions_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -775,7 +786,6 @@ def test_batch_create_sessions_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = spanner.BatchCreateSessionsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_create_sessions( @@ -786,14 +796,12 @@ def test_batch_create_sessions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" - assert args[0].session_count == 1420 def test_batch_create_sessions_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -807,7 +815,7 @@ def test_batch_create_sessions_flattened_error(): @pytest.mark.asyncio async def test_batch_create_sessions_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -829,15 +837,13 @@ async def test_batch_create_sessions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" - assert args[0].session_count == 1420 @pytest.mark.asyncio async def test_batch_create_sessions_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -851,7 +857,7 @@ async def test_batch_create_sessions_flattened_error_async(): def test_get_session(transport: str = "grpc", request_type=spanner.GetSessionRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -862,19 +868,15 @@ def test_get_session(transport: str = "grpc", request_type=spanner.GetSessionReq with mock.patch.object(type(client.transport.get_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.Session(name="name_value",) - response = client.get_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.GetSessionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.Session) - assert response.name == "name_value" @@ -886,7 +888,7 @@ def test_get_session_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -894,7 +896,6 @@ def test_get_session_empty_call(): client.get_session() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.GetSessionRequest() @@ -903,7 +904,7 @@ async def test_get_session_async( transport: str = "grpc_asyncio", request_type=spanner.GetSessionRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -916,18 +917,15 @@ async def test_get_session_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.Session(name="name_value",) ) - response = await client.get_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.GetSessionRequest() # Establish that the response is the type that we expect. assert isinstance(response, spanner.Session) - assert response.name == "name_value" @@ -937,17 +935,17 @@ async def test_get_session_async_from_dict(): def test_get_session_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.GetSessionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_session), "__call__") as call: call.return_value = spanner.Session() - client.get_session(request) # Establish that the underlying gRPC stub method was called. @@ -962,17 +960,17 @@ def test_get_session_field_headers(): @pytest.mark.asyncio async def test_get_session_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.GetSessionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_session), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(spanner.Session()) - await client.get_session(request) # Establish that the underlying gRPC stub method was called. @@ -986,13 +984,12 @@ async def test_get_session_field_headers_async(): def test_get_session_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.Session() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_session(name="name_value",) @@ -1001,12 +998,11 @@ def test_get_session_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_session_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1018,7 +1014,7 @@ def test_get_session_flattened_error(): @pytest.mark.asyncio async def test_get_session_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_session), "__call__") as call: @@ -1034,13 +1030,12 @@ async def test_get_session_flattened_async(): # 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_session_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1054,7 +1049,7 @@ def test_list_sessions( transport: str = "grpc", request_type=spanner.ListSessionsRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1067,19 +1062,15 @@ def test_list_sessions( call.return_value = spanner.ListSessionsResponse( next_page_token="next_page_token_value", ) - response = client.list_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ListSessionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionsPager) - assert response.next_page_token == "next_page_token_value" @@ -1091,7 +1082,7 @@ def test_list_sessions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1099,7 +1090,6 @@ def test_list_sessions_empty_call(): client.list_sessions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ListSessionsRequest() @@ -1108,7 +1098,7 @@ async def test_list_sessions_async( transport: str = "grpc_asyncio", request_type=spanner.ListSessionsRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1121,18 +1111,15 @@ async def test_list_sessions_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.ListSessionsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ListSessionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSessionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1142,17 +1129,17 @@ async def test_list_sessions_async_from_dict(): def test_list_sessions_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ListSessionsRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sessions), "__call__") as call: call.return_value = spanner.ListSessionsResponse() - client.list_sessions(request) # Establish that the underlying gRPC stub method was called. @@ -1167,11 +1154,12 @@ def test_list_sessions_field_headers(): @pytest.mark.asyncio async def test_list_sessions_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ListSessionsRequest() + request.database = "database/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1179,7 +1167,6 @@ async def test_list_sessions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.ListSessionsResponse() ) - await client.list_sessions(request) # Establish that the underlying gRPC stub method was called. @@ -1193,13 +1180,12 @@ async def test_list_sessions_field_headers_async(): def test_list_sessions_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sessions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.ListSessionsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_sessions(database="database_value",) @@ -1208,12 +1194,11 @@ def test_list_sessions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" def test_list_sessions_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1225,7 +1210,7 @@ def test_list_sessions_flattened_error(): @pytest.mark.asyncio async def test_list_sessions_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sessions), "__call__") as call: @@ -1243,13 +1228,12 @@ async def test_list_sessions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].database == "database_value" @pytest.mark.asyncio async def test_list_sessions_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1260,7 +1244,7 @@ async def test_list_sessions_flattened_error_async(): def test_list_sessions_pager(): - client = SpannerClient(credentials=credentials.AnonymousCredentials,) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sessions), "__call__") as call: @@ -1294,7 +1278,7 @@ def test_list_sessions_pager(): def test_list_sessions_pages(): - client = SpannerClient(credentials=credentials.AnonymousCredentials,) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sessions), "__call__") as call: @@ -1320,7 +1304,7 @@ def test_list_sessions_pages(): @pytest.mark.asyncio async def test_list_sessions_async_pager(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1353,7 +1337,7 @@ async def test_list_sessions_async_pager(): @pytest.mark.asyncio async def test_list_sessions_async_pages(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1385,7 +1369,7 @@ def test_delete_session( transport: str = "grpc", request_type=spanner.DeleteSessionRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1396,13 +1380,11 @@ def test_delete_session( with mock.patch.object(type(client.transport.delete_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.DeleteSessionRequest() # Establish that the response is the type that we expect. @@ -1417,7 +1399,7 @@ def test_delete_session_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1425,7 +1407,6 @@ def test_delete_session_empty_call(): client.delete_session() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.DeleteSessionRequest() @@ -1434,7 +1415,7 @@ async def test_delete_session_async( transport: str = "grpc_asyncio", request_type=spanner.DeleteSessionRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1445,13 +1426,11 @@ async def test_delete_session_async( with mock.patch.object(type(client.transport.delete_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.DeleteSessionRequest() # Establish that the response is the type that we expect. @@ -1464,17 +1443,17 @@ async def test_delete_session_async_from_dict(): def test_delete_session_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.DeleteSessionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_session), "__call__") as call: call.return_value = None - client.delete_session(request) # Establish that the underlying gRPC stub method was called. @@ -1489,17 +1468,17 @@ def test_delete_session_field_headers(): @pytest.mark.asyncio async def test_delete_session_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.DeleteSessionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_session), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_session(request) # Establish that the underlying gRPC stub method was called. @@ -1513,13 +1492,12 @@ async def test_delete_session_field_headers_async(): def test_delete_session_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_session), "__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_session(name="name_value",) @@ -1528,12 +1506,11 @@ def test_delete_session_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_session_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1545,7 +1522,7 @@ def test_delete_session_flattened_error(): @pytest.mark.asyncio async def test_delete_session_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_session), "__call__") as call: @@ -1561,13 +1538,12 @@ async def test_delete_session_flattened_async(): # 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_session_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1579,7 +1555,7 @@ async def test_delete_session_flattened_error_async(): def test_execute_sql(transport: str = "grpc", request_type=spanner.ExecuteSqlRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1590,17 +1566,14 @@ def test_execute_sql(transport: str = "grpc", request_type=spanner.ExecuteSqlReq with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = result_set.ResultSet() - response = client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() # Establish that the response is the type that we expect. - assert isinstance(response, result_set.ResultSet) @@ -1612,7 +1585,7 @@ def test_execute_sql_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1620,7 +1593,6 @@ def test_execute_sql_empty_call(): client.execute_sql() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() @@ -1629,7 +1601,7 @@ async def test_execute_sql_async( transport: str = "grpc_asyncio", request_type=spanner.ExecuteSqlRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1642,13 +1614,11 @@ async def test_execute_sql_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( result_set.ResultSet() ) - response = await client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() # Establish that the response is the type that we expect. @@ -1661,17 +1631,17 @@ async def test_execute_sql_async_from_dict(): def test_execute_sql_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteSqlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: call.return_value = result_set.ResultSet() - client.execute_sql(request) # Establish that the underlying gRPC stub method was called. @@ -1686,11 +1656,12 @@ def test_execute_sql_field_headers(): @pytest.mark.asyncio async def test_execute_sql_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteSqlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1698,7 +1669,6 @@ async def test_execute_sql_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( result_set.ResultSet() ) - await client.execute_sql(request) # Establish that the underlying gRPC stub method was called. @@ -1715,7 +1685,7 @@ def test_execute_streaming_sql( transport: str = "grpc", request_type=spanner.ExecuteSqlRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1728,13 +1698,11 @@ def test_execute_streaming_sql( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([result_set.PartialResultSet()]) - response = client.execute_streaming_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() # Establish that the response is the type that we expect. @@ -1750,7 +1718,7 @@ def test_execute_streaming_sql_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1760,7 +1728,6 @@ def test_execute_streaming_sql_empty_call(): client.execute_streaming_sql() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() @@ -1769,7 +1736,7 @@ async def test_execute_streaming_sql_async( transport: str = "grpc_asyncio", request_type=spanner.ExecuteSqlRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1785,13 +1752,11 @@ async def test_execute_streaming_sql_async( call.return_value.read = mock.AsyncMock( side_effect=[result_set.PartialResultSet()] ) - response = await client.execute_streaming_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteSqlRequest() # Establish that the response is the type that we expect. @@ -1805,11 +1770,12 @@ async def test_execute_streaming_sql_async_from_dict(): def test_execute_streaming_sql_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteSqlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1817,7 +1783,6 @@ def test_execute_streaming_sql_field_headers(): type(client.transport.execute_streaming_sql), "__call__" ) as call: call.return_value = iter([result_set.PartialResultSet()]) - client.execute_streaming_sql(request) # Establish that the underlying gRPC stub method was called. @@ -1832,11 +1797,12 @@ def test_execute_streaming_sql_field_headers(): @pytest.mark.asyncio async def test_execute_streaming_sql_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteSqlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1847,7 +1813,6 @@ async def test_execute_streaming_sql_field_headers_async(): call.return_value.read = mock.AsyncMock( side_effect=[result_set.PartialResultSet()] ) - await client.execute_streaming_sql(request) # Establish that the underlying gRPC stub method was called. @@ -1864,7 +1829,7 @@ def test_execute_batch_dml( transport: str = "grpc", request_type=spanner.ExecuteBatchDmlRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1877,17 +1842,14 @@ def test_execute_batch_dml( ) as call: # Designate an appropriate return value for the call. call.return_value = spanner.ExecuteBatchDmlResponse() - response = client.execute_batch_dml(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteBatchDmlRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.ExecuteBatchDmlResponse) @@ -1899,7 +1861,7 @@ def test_execute_batch_dml_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1909,7 +1871,6 @@ def test_execute_batch_dml_empty_call(): client.execute_batch_dml() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteBatchDmlRequest() @@ -1918,7 +1879,7 @@ async def test_execute_batch_dml_async( transport: str = "grpc_asyncio", request_type=spanner.ExecuteBatchDmlRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1933,13 +1894,11 @@ async def test_execute_batch_dml_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.ExecuteBatchDmlResponse() ) - response = await client.execute_batch_dml(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ExecuteBatchDmlRequest() # Establish that the response is the type that we expect. @@ -1952,11 +1911,12 @@ async def test_execute_batch_dml_async_from_dict(): def test_execute_batch_dml_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteBatchDmlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1964,7 +1924,6 @@ def test_execute_batch_dml_field_headers(): type(client.transport.execute_batch_dml), "__call__" ) as call: call.return_value = spanner.ExecuteBatchDmlResponse() - client.execute_batch_dml(request) # Establish that the underlying gRPC stub method was called. @@ -1979,11 +1938,12 @@ def test_execute_batch_dml_field_headers(): @pytest.mark.asyncio async def test_execute_batch_dml_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ExecuteBatchDmlRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1993,7 +1953,6 @@ async def test_execute_batch_dml_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.ExecuteBatchDmlResponse() ) - await client.execute_batch_dml(request) # Establish that the underlying gRPC stub method was called. @@ -2008,7 +1967,7 @@ async def test_execute_batch_dml_field_headers_async(): def test_read(transport: str = "grpc", request_type=spanner.ReadRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2019,17 +1978,14 @@ def test_read(transport: str = "grpc", request_type=spanner.ReadRequest): with mock.patch.object(type(client.transport.read), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = result_set.ResultSet() - response = client.read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() # Establish that the response is the type that we expect. - assert isinstance(response, result_set.ResultSet) @@ -2041,7 +1997,7 @@ def test_read_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2049,7 +2005,6 @@ def test_read_empty_call(): client.read() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() @@ -2058,7 +2013,7 @@ async def test_read_async( transport: str = "grpc_asyncio", request_type=spanner.ReadRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2071,13 +2026,11 @@ async def test_read_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( result_set.ResultSet() ) - response = await client.read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() # Establish that the response is the type that we expect. @@ -2090,17 +2043,17 @@ async def test_read_async_from_dict(): def test_read_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.read), "__call__") as call: call.return_value = result_set.ResultSet() - client.read(request) # Establish that the underlying gRPC stub method was called. @@ -2115,11 +2068,12 @@ def test_read_field_headers(): @pytest.mark.asyncio async def test_read_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2127,7 +2081,6 @@ async def test_read_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( result_set.ResultSet() ) - await client.read(request) # Establish that the underlying gRPC stub method was called. @@ -2142,7 +2095,7 @@ async def test_read_field_headers_async(): def test_streaming_read(transport: str = "grpc", request_type=spanner.ReadRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2153,13 +2106,11 @@ def test_streaming_read(transport: str = "grpc", request_type=spanner.ReadReques with mock.patch.object(type(client.transport.streaming_read), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = iter([result_set.PartialResultSet()]) - response = client.streaming_read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() # Establish that the response is the type that we expect. @@ -2175,7 +2126,7 @@ def test_streaming_read_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2183,7 +2134,6 @@ def test_streaming_read_empty_call(): client.streaming_read() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() @@ -2192,7 +2142,7 @@ async def test_streaming_read_async( transport: str = "grpc_asyncio", request_type=spanner.ReadRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2206,13 +2156,11 @@ async def test_streaming_read_async( call.return_value.read = mock.AsyncMock( side_effect=[result_set.PartialResultSet()] ) - response = await client.streaming_read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.ReadRequest() # Establish that the response is the type that we expect. @@ -2226,17 +2174,17 @@ async def test_streaming_read_async_from_dict(): def test_streaming_read_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.streaming_read), "__call__") as call: call.return_value = iter([result_set.PartialResultSet()]) - client.streaming_read(request) # Establish that the underlying gRPC stub method was called. @@ -2251,11 +2199,12 @@ def test_streaming_read_field_headers(): @pytest.mark.asyncio async def test_streaming_read_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.ReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2264,7 +2213,6 @@ async def test_streaming_read_field_headers_async(): call.return_value.read = mock.AsyncMock( side_effect=[result_set.PartialResultSet()] ) - await client.streaming_read(request) # Establish that the underlying gRPC stub method was called. @@ -2281,7 +2229,7 @@ def test_begin_transaction( transport: str = "grpc", request_type=spanner.BeginTransactionRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2294,19 +2242,15 @@ def test_begin_transaction( ) as call: # Designate an appropriate return value for the call. call.return_value = transaction.Transaction(id=b"id_blob",) - response = client.begin_transaction(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BeginTransactionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, transaction.Transaction) - assert response.id == b"id_blob" @@ -2318,7 +2262,7 @@ def test_begin_transaction_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2328,7 +2272,6 @@ def test_begin_transaction_empty_call(): client.begin_transaction() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BeginTransactionRequest() @@ -2337,7 +2280,7 @@ async def test_begin_transaction_async( transport: str = "grpc_asyncio", request_type=spanner.BeginTransactionRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2352,18 +2295,15 @@ async def test_begin_transaction_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transaction.Transaction(id=b"id_blob",) ) - response = await client.begin_transaction(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.BeginTransactionRequest() # Establish that the response is the type that we expect. assert isinstance(response, transaction.Transaction) - assert response.id == b"id_blob" @@ -2373,11 +2313,12 @@ async def test_begin_transaction_async_from_dict(): def test_begin_transaction_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.BeginTransactionRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2385,7 +2326,6 @@ def test_begin_transaction_field_headers(): type(client.transport.begin_transaction), "__call__" ) as call: call.return_value = transaction.Transaction() - client.begin_transaction(request) # Establish that the underlying gRPC stub method was called. @@ -2400,11 +2340,12 @@ def test_begin_transaction_field_headers(): @pytest.mark.asyncio async def test_begin_transaction_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.BeginTransactionRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2414,7 +2355,6 @@ async def test_begin_transaction_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transaction.Transaction() ) - await client.begin_transaction(request) # Establish that the underlying gRPC stub method was called. @@ -2428,7 +2368,7 @@ async def test_begin_transaction_field_headers_async(): def test_begin_transaction_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2436,7 +2376,6 @@ def test_begin_transaction_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = transaction.Transaction() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.begin_transaction( @@ -2448,14 +2387,12 @@ def test_begin_transaction_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].options == transaction.TransactionOptions(read_write=None) def test_begin_transaction_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2469,7 +2406,7 @@ def test_begin_transaction_flattened_error(): @pytest.mark.asyncio async def test_begin_transaction_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2492,15 +2429,13 @@ async def test_begin_transaction_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].options == transaction.TransactionOptions(read_write=None) @pytest.mark.asyncio async def test_begin_transaction_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2514,7 +2449,7 @@ async def test_begin_transaction_flattened_error_async(): def test_commit(transport: str = "grpc", request_type=spanner.CommitRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2524,19 +2459,16 @@ def test_commit(transport: str = "grpc", request_type=spanner.CommitRequest): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.commit), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = spanner.CommitResponse() - + call.return_value = commit_response.CommitResponse() response = client.commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CommitRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, spanner.CommitResponse) + assert isinstance(response, commit_response.CommitResponse) def test_commit_from_dict(): @@ -2547,7 +2479,7 @@ def test_commit_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2555,7 +2487,6 @@ def test_commit_empty_call(): client.commit() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CommitRequest() @@ -2564,7 +2495,7 @@ async def test_commit_async( transport: str = "grpc_asyncio", request_type=spanner.CommitRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2575,19 +2506,17 @@ async def test_commit_async( with mock.patch.object(type(client.transport.commit), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - spanner.CommitResponse() + commit_response.CommitResponse() ) - response = await client.commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.CommitRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.CommitResponse) + assert isinstance(response, commit_response.CommitResponse) @pytest.mark.asyncio @@ -2596,17 +2525,17 @@ async def test_commit_async_from_dict(): def test_commit_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.CommitRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.commit), "__call__") as call: - call.return_value = spanner.CommitResponse() - + call.return_value = commit_response.CommitResponse() client.commit(request) # Establish that the underlying gRPC stub method was called. @@ -2621,19 +2550,19 @@ def test_commit_field_headers(): @pytest.mark.asyncio async def test_commit_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.CommitRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.commit), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - spanner.CommitResponse() + commit_response.CommitResponse() ) - await client.commit(request) # Establish that the underlying gRPC stub method was called. @@ -2647,13 +2576,12 @@ async def test_commit_field_headers_async(): def test_commit_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.commit), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = spanner.CommitResponse() - + call.return_value = commit_response.CommitResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.commit( @@ -2669,20 +2597,17 @@ def test_commit_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].mutations == [ mutation.Mutation(insert=mutation.Mutation.Write(table="table_value")) ] - assert args[0].single_use_transaction == transaction.TransactionOptions( read_write=None ) def test_commit_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2700,15 +2625,15 @@ def test_commit_flattened_error(): @pytest.mark.asyncio async def test_commit_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.commit), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = spanner.CommitResponse() + call.return_value = commit_response.CommitResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - spanner.CommitResponse() + commit_response.CommitResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2725,13 +2650,10 @@ async def test_commit_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].mutations == [ mutation.Mutation(insert=mutation.Mutation.Write(table="table_value")) ] - assert args[0].single_use_transaction == transaction.TransactionOptions( read_write=None ) @@ -2739,7 +2661,7 @@ async def test_commit_flattened_async(): @pytest.mark.asyncio async def test_commit_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2757,7 +2679,7 @@ async def test_commit_flattened_error_async(): def test_rollback(transport: str = "grpc", request_type=spanner.RollbackRequest): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2768,13 +2690,11 @@ def test_rollback(transport: str = "grpc", request_type=spanner.RollbackRequest) with mock.patch.object(type(client.transport.rollback), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.rollback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.RollbackRequest() # Establish that the response is the type that we expect. @@ -2789,7 +2709,7 @@ def test_rollback_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2797,7 +2717,6 @@ def test_rollback_empty_call(): client.rollback() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.RollbackRequest() @@ -2806,7 +2725,7 @@ async def test_rollback_async( transport: str = "grpc_asyncio", request_type=spanner.RollbackRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2817,13 +2736,11 @@ async def test_rollback_async( with mock.patch.object(type(client.transport.rollback), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.rollback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.RollbackRequest() # Establish that the response is the type that we expect. @@ -2836,17 +2753,17 @@ async def test_rollback_async_from_dict(): def test_rollback_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.RollbackRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.rollback), "__call__") as call: call.return_value = None - client.rollback(request) # Establish that the underlying gRPC stub method was called. @@ -2861,17 +2778,17 @@ def test_rollback_field_headers(): @pytest.mark.asyncio async def test_rollback_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.RollbackRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.rollback), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.rollback(request) # Establish that the underlying gRPC stub method was called. @@ -2885,13 +2802,12 @@ async def test_rollback_field_headers_async(): def test_rollback_flattened(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.rollback), "__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.rollback( @@ -2902,14 +2818,12 @@ def test_rollback_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].transaction_id == b"transaction_id_blob" def test_rollback_flattened_error(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2923,7 +2837,7 @@ def test_rollback_flattened_error(): @pytest.mark.asyncio async def test_rollback_flattened_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.rollback), "__call__") as call: @@ -2941,15 +2855,13 @@ async def test_rollback_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].transaction_id == b"transaction_id_blob" @pytest.mark.asyncio async def test_rollback_flattened_error_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2965,7 +2877,7 @@ def test_partition_query( transport: str = "grpc", request_type=spanner.PartitionQueryRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2976,17 +2888,14 @@ def test_partition_query( with mock.patch.object(type(client.transport.partition_query), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.PartitionResponse() - response = client.partition_query(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionQueryRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.PartitionResponse) @@ -2998,7 +2907,7 @@ def test_partition_query_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3006,7 +2915,6 @@ def test_partition_query_empty_call(): client.partition_query() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionQueryRequest() @@ -3015,7 +2923,7 @@ async def test_partition_query_async( transport: str = "grpc_asyncio", request_type=spanner.PartitionQueryRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3028,13 +2936,11 @@ async def test_partition_query_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.PartitionResponse() ) - response = await client.partition_query(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionQueryRequest() # Establish that the response is the type that we expect. @@ -3047,17 +2953,17 @@ async def test_partition_query_async_from_dict(): def test_partition_query_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.PartitionQueryRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.partition_query), "__call__") as call: call.return_value = spanner.PartitionResponse() - client.partition_query(request) # Establish that the underlying gRPC stub method was called. @@ -3072,11 +2978,12 @@ def test_partition_query_field_headers(): @pytest.mark.asyncio async def test_partition_query_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.PartitionQueryRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3084,7 +2991,6 @@ async def test_partition_query_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.PartitionResponse() ) - await client.partition_query(request) # Establish that the underlying gRPC stub method was called. @@ -3101,7 +3007,7 @@ def test_partition_read( transport: str = "grpc", request_type=spanner.PartitionReadRequest ): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3112,17 +3018,14 @@ def test_partition_read( with mock.patch.object(type(client.transport.partition_read), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = spanner.PartitionResponse() - response = client.partition_read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionReadRequest() # Establish that the response is the type that we expect. - assert isinstance(response, spanner.PartitionResponse) @@ -3134,7 +3037,7 @@ def test_partition_read_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3142,7 +3045,6 @@ def test_partition_read_empty_call(): client.partition_read() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionReadRequest() @@ -3151,7 +3053,7 @@ async def test_partition_read_async( transport: str = "grpc_asyncio", request_type=spanner.PartitionReadRequest ): client = SpannerAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3164,13 +3066,11 @@ async def test_partition_read_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.PartitionResponse() ) - response = await client.partition_read(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == spanner.PartitionReadRequest() # Establish that the response is the type that we expect. @@ -3183,17 +3083,17 @@ async def test_partition_read_async_from_dict(): def test_partition_read_field_headers(): - client = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.PartitionReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.partition_read), "__call__") as call: call.return_value = spanner.PartitionResponse() - client.partition_read(request) # Establish that the underlying gRPC stub method was called. @@ -3208,11 +3108,12 @@ def test_partition_read_field_headers(): @pytest.mark.asyncio async def test_partition_read_field_headers_async(): - client = SpannerAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = spanner.PartitionReadRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3220,7 +3121,6 @@ async def test_partition_read_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( spanner.PartitionResponse() ) - await client.partition_read(request) # Establish that the underlying gRPC stub method was called. @@ -3236,16 +3136,16 @@ async def test_partition_read_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpannerGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SpannerGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpannerClient( @@ -3255,7 +3155,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SpannerGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpannerClient( @@ -3266,7 +3166,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SpannerGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SpannerClient(transport=transport) assert client.transport is transport @@ -3275,13 +3175,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SpannerGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SpannerGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3293,23 +3193,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = SpannerClient(credentials=credentials.AnonymousCredentials(),) + client = SpannerClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SpannerGrpcTransport,) def test_spanner_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SpannerTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3321,7 +3221,7 @@ def test_spanner_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SpannerTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3348,15 +3248,40 @@ def test_spanner_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_spanner_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.spanner_v1.services.spanner.transports.SpannerTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SpannerTransport( + 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", + "https://www.googleapis.com/auth/spanner.data", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_spanner_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.spanner_v1.services.spanner.transports.SpannerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpannerTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3372,19 +3297,36 @@ def test_spanner_base_transport_with_credentials_file(): def test_spanner_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.spanner_v1.services.spanner.transports.SpannerTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpannerTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_spanner_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SpannerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.data", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_spanner_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SpannerClient() adc.assert_called_once_with( scopes=( @@ -3395,14 +3337,38 @@ def test_spanner_auth_adc(): ) -def test_spanner_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SpannerGrpcTransport, transports.SpannerGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_spanner_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SpannerGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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", + "https://www.googleapis.com/auth/spanner.data", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SpannerGrpcTransport, transports.SpannerGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_spanner_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -3412,12 +3378,123 @@ def test_spanner_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpannerGrpcTransport, grpc_helpers), + (transports.SpannerGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_spanner_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( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.data", + ), + scopes=["1", "2"], + default_host="spanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpannerGrpcTransport, grpc_helpers), + (transports.SpannerGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_spanner_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/spanner.data", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpannerGrpcTransport, grpc_helpers), + (transports.SpannerGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_spanner_transport_create_channel_user_scopes(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( + "spanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SpannerGrpcTransport, transports.SpannerGrpcAsyncIOTransport], ) def test_spanner_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3459,7 +3536,7 @@ def test_spanner_grpc_transport_client_cert_source_for_mtls(transport_class): def test_spanner_host_no_port(): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com" ), @@ -3469,7 +3546,7 @@ def test_spanner_host_no_port(): def test_spanner_host_with_port(): client = SpannerClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="spanner.googleapis.com:8000" ), @@ -3520,9 +3597,9 @@ def test_spanner_transport_channel_mtls_with_client_cert_source(transport_class) mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3603,7 +3680,6 @@ def test_database_path(): project = "squid" instance = "clam" database = "whelk" - expected = "projects/{project}/instances/{instance}/databases/{database}".format( project=project, instance=instance, database=database, ) @@ -3629,7 +3705,6 @@ def test_session_path(): instance = "mussel" database = "winkle" session = "nautilus" - expected = "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}".format( project=project, instance=instance, database=database, session=session, ) @@ -3653,7 +3728,6 @@ def test_parse_session_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3674,7 +3748,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = SpannerClient.common_folder_path(folder) assert expected == actual @@ -3693,7 +3766,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = SpannerClient.common_organization_path(organization) assert expected == actual @@ -3712,7 +3784,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = SpannerClient.common_project_path(project) assert expected == actual @@ -3732,7 +3803,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3759,7 +3829,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SpannerTransport, "_prep_wrapped_messages" ) as prep: client = SpannerClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3768,6 +3838,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SpannerClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)